RS / HEG / RPU Toy Lab — Full Reference

Machine-readable mirror of the RS Toy Lab site. Every section, toy, and toy source file is expanded inline — nothing is hidden behind display:none or a click handler. Content order matches the live site. Canonical human-facing site: https://icpub.org/.

01 — Home: Reasoning Substrate Lab

The Reasoning Substrate is a deterministic reasoning layer — a model-agnostic, language-agnostic state machine that structures how systems take reasoning steps. It integrates cleanly with existing architectures, guiding or supporting them to produce more stable, predictable, and reliable reasoning.

This lab hosts conceptual toys — self-contained, browser-runnable simulations demonstrating the RS, HEG, and RPU architectures in isolation. Each toy is a proof-of-concept harness that makes one architectural idea visible and interactive. Nothing here is production code. Everything here is deterministic.

What is a toy? A minimal, fully self-contained HTML/JS simulation demonstrating one specific behavior of the substrate — auditable, replayable, no external dependencies, no network calls.

What is the HEG? The Human Expression Gateway converts raw human expression — text, audio, gesture, prosody — into typed Cognitive Action Packets (CAPs) via a deterministic operator pipeline: SEGMENT → ACT → TARGET → EMOTION → PATTERN → CAP_BUILD.

What is the RPU? Reasoning Processing Units are a proposed class of hardware accelerators, conceptually designed to execute the Reasoning Substrate (RS) update cycle directly in silicon. RPU Classic is defined around contraction-based deterministic convergence, while RPU Quantum is defined around energy-guided perturbation to escape shallow traps. Our current work focuses on the mathematical architecture and patent foundation for these units, with hardware implementations treated as future targets rather than existing products.

Status badges: RS v1, RS v2, HEG, RPU, LITE — BY REQUEST

02 — Testing Center

All modules below are TOY-grade — browser-runnable, fully sandboxed, no network calls. Click [ EXPAND ] on any toy to load and run it inline.

Hero Toy — 100× Deterministic Replay

This LITE artifact showcases the core physics of the RS substrate: deterministic state evolution, invariant-bounded collapse, fixed-point stability, fault-tolerant safe-return, and replayable audit traces. It is designed as a minimal, inspectable runtime that can be crashed, resumed, replayed, diffed, and exported — allowing engineers to verify substrate behavior directly, without models, heuristics, or optimization. Every step depends only on (state, tick), enabling bit-for-bit identical trajectories across runs and full recovery from interruption. This is the public slice of the substrate: a reliability and safety demonstration built for hyperscalers evaluating deterministic reasoning systems.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>RSv2-LITE Determinism Stability Safe-Return</title>
<style>
:root {
  --amber: #ffb86c; --amber-soft: #f1a85a; --amber-dim: #c28a4a;
  --danger: #ff5555; --ok: #50fa7b;
  --bg-page: #050302; --bg-panel: #120b06; --border: #3a2614;
}
body {
  background: var(--bg-page); color: var(--amber);
  font-family: "IBM Plex Mono","SF Mono",Menlo,monospace;
  text-transform: uppercase; letter-spacing: 0.06em; padding: 0.75rem;
}
body::before {
  content:""; position:fixed; inset:0; pointer-events:none;
  background-image: repeating-linear-gradient(to bottom, rgba(0,0,0,0.25) 0, rgba(0,0,0,0.25) 1px, transparent 2px, transparent 3px);
  mix-blend-mode: multiply;
}
body::after {
  content:""; position:fixed; inset:0; pointer-events:none;
  background: radial-gradient(circle at top, rgba(255,184,108,0.18) 0, transparent 55%);
}
h1 { color: var(--amber); font-size: 1.1rem; margin: 0 0 0.3rem 0; }
h2 { color: var(--amber-soft); font-size: 0.85rem; margin: 0 0 0.4rem 0; }
.main-grid {
  display: grid; grid-template-columns: 1.1fr 1fr 1.1fr;
  gap: 0.6rem; margin-top: 0.6rem;
}
.panel {
  background: radial-gradient(circle at top, #1b1008 0, #0a0503 70%);
  border: 1px solid var(--border); border-radius: 8px; padding: 0.6rem;
  box-shadow: 0 0 6px rgba(255,184,108,0.18) inset;
}
button {
  background: #3a2614; color: var(--amber); border: 1px solid var(--border);
  border-radius: 4px; padding: 0.35rem 0.7rem; font-size: 0.75rem;
  text-transform: uppercase; letter-spacing: 0.08em; cursor: pointer;
  margin: 0 0.35rem 0.4rem 0; font-family: inherit;
}
button:hover { background: #4a311b; box-shadow: 0 0 8px rgba(255,184,108,0.4); transform: translateY(-1px); }
button:disabled { opacity: 0.4; cursor: default; }
.log {
  background: #050302; border-radius: 4px; padding: 0.4rem;
  color: var(--amber); font-size: 0.7rem; white-space: pre-wrap;
  overflow: auto; max-height: 260px; box-shadow: 0 0 6px rgba(255,184,108,0.18) inset;
}
.narrator { font-size: 0.7rem; color: var(--amber-soft); }
.badge-ok { color: var(--ok); }
.badge-error { color: var(--danger); }
</style>
<style>
/* === RS AMBER CRT THEME (injected per Style Guide) === */
:root{--amber:#ffb86c;--amber-soft:#f1a85a;--amber-dim:#c28a4a;--bg:#050302;--bg-panel:#120b06;--border:#3a2614;--danger:#ff5555;--ok:#50fa7b;}
html,body{background:var(--bg) !important;color:var(--amber) !important;font-family:"IBM Plex Mono","SF Mono",Menlo,Consolas,monospace !important;}
body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:9998;background:repeating-linear-gradient(to bottom,rgba(0,0,0,0.25) 0,rgba(0,0,0,0.25) 1px,transparent 2px,transparent 3px);mix-blend-mode:multiply;}
body::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:9999;background:radial-gradient(circle at top,rgba(255,184,108,0.16) 0%,transparent 55%);}
h1,h2,h3{color:var(--amber) !important;text-transform:uppercase;letter-spacing:0.08em;text-shadow:0 0 6px rgba(255,184,108,0.4);}
h1{font-size:1.1rem !important;} h2{font-size:0.9rem !important;color:var(--amber-soft) !important;}
p,div,span,label,td,th,li{color:var(--amber) !important;}
.panel,.card,.section,.box,.grid>div{background:radial-gradient(circle at top,#1b1008 0%,#0a0503 70%) !important;border:1px solid var(--border) !important;border-radius:8px !important;box-shadow:0 0 6px rgba(255,184,108,0.18) inset !important;}
button{background:#3a2614 !important;color:var(--amber) !important;border:1px solid var(--border) !important;border-radius:4px !important;font-family:inherit !important;text-transform:uppercase;letter-spacing:0.08em;cursor:pointer;transition:all 0.15s;}
button:hover{background:#4a311b !important;box-shadow:0 0 8px rgba(255,184,108,0.4);transform:translateY(-1px);}
button:disabled{opacity:0.4 !important;}
pre,.log,.logbox,.output,textarea,input,select,code{background:#050302 !important;color:var(--amber) !important;border:1px solid var(--border) !important;font-family:inherit !important;}
.tag,.pill,.badge{border:1px solid var(--border) !important;background:#1a0d06 !important;color:var(--amber-soft) !important;}
.bar-wrap{background:#1b1008 !important;} .bar{background:var(--amber) !important;}
a{color:var(--amber-soft) !important;}
::-webkit-scrollbar{width:8px;height:8px;} ::-webkit-scrollbar-track{background:#0a0503;} ::-webkit-scrollbar-thumb{background:#3a2614;border-radius:4px;}

</style>
</head>
<body>
<h1>RSv2-LITE · Determinism · Stability · Safe-Return</h1>
<div class="narrator" id="narrator">READY · substrate idle · start a run to see deterministic physics</div>
<div class="main-grid">
  <div class="panel">
    <h2>Controls</h2>
    <button onclick="runDeterministicReplay()">Deterministic Replay</button>
    <button onclick="startRun()">Start Run</button>
    <button onclick="killRun()">Kill Process</button>
    <button onclick="resumeFromAudit()">Resume From Audit</button>
    <button onclick="runParallel()">Run Parallel Reference</button>
    <button onclick="diffRuns()">Diff Trajectories</button>
    <button onclick="exportAudit()">Export Audit Log</button>
  </div>
  <div class="panel">
    <h2>Primary Run · Agent State</h2>
    <div class="log" id="log_main"></div>
    <h2 style="margin-top:0.6rem;">Parallel Reference</h2>
    <div class="log" id="log_parallel"></div>
  </div>
  <div class="panel">
    <h2>Audit · Replay · Diff</h2>
    <div class="log" id="log_audit"></div>
    <h2 style="margin-top:0.6rem;">Diff</h2>
    <div class="log" id="log_diff"></div>
  </div>
</div>
<script>
function clamp(s){return{x:Math.max(Math.min(s.x,10),-10),y:Math.max(Math.min(s.y,10),-10),z:Math.max(Math.min(s.z,10),-10)};}
function invariant(p,c){return Math.abs(c.x)+Math.abs(c.y)+Math.abs(c.z)<=Math.abs(p.x)+Math.abs(p.y)+Math.abs(p.z)+0.05;}
function fixedPoint(a,b){return(Math.abs(a.x-b.x)+Math.abs(a.y-b.y)+Math.abs(a.z-b.z))<1e-9;}
function generateCandidates(s,t){var out=[];for(var k=0;k<4;k++){var ph=(t+k)%4,sg=ph<2?1:-1;out.push({x:s.x+sg*0.03,y:s.y+((t+k)%3===0?0.02:-0.02),z:s.z+((t+k)%5===0?0.01:-0.01)});}return out;}
function collapse(cands,prev){for(var i=0;i<cands.length;i++)if(invariant(prev,cands[i]))return cands[i];return prev;}
function setNarrator(msg){document.getElementById('narrator').textContent=msg;}
function logTo(id,msg){var el=document.getElementById(id);el.textContent+=msg+'\n';el.scrollTop=el.scrollHeight;}
function clearLogs(){['log_audit','log_main','log_parallel','log_diff'].forEach(function(id){document.getElementById(id).textContent='';});}
var db;
function initDB(){var req=indexedDB.open('rsv2_lite_db',1);req.onupgradeneeded=function(e){var d=e.target.result;if(!d.objectStoreNames.contains('audit'))d.createObjectStore('audit',{keyPath:'id'});};req.onsuccess=function(e){db=e.target.result;};}
initDB();
function persistEntry(entry){if(!db)return;var tx=db.transaction('audit','readwrite');tx.objectStore('audit').put({id:entry.tick,entry:entry});}
function loadDB(cb){if(!db){cb([]);return;}var req=db.transaction('audit','readonly').objectStore('audit').getAll();req.onsuccess=function(){cb(req.result.sort(function(a,b){return a.id-b.id;}).map(function(r){return r.entry;}));};}
function runDeterministicReplay(){
  clearLogs();setNarrator('DETERMINISTIC REPLAY · 100 RUNS · VERIFYING BIT-FOR-BIT TRAJECTORIES');
  logTo('log_audit','=== Deterministic Replay: 100x identical traces ===');
  var runs=100,turns=200,traces=[];
  for(var r=0;r<runs;r++){var s={x:0,y:0,z:0},trace=[];for(var t=0;t<turns;t++){var b=clamp(s),c=generateCandidates(b,t),n=collapse(c,b);trace.push({tick:t,state:{x:s.x,y:s.y,z:s.z},next:{x:n.x,y:n.y,z:n.z},fixed:fixedPoint(s,n)});s=n;}traces.push(trace);}
  var ref=JSON.stringify(traces[0]),equal=traces.every(function(t){return JSON.stringify(t)===ref;});
  logTo('log_audit',equal?'Replay Verified: PASS (100/100 identical traces)':'Replay Verified: FAIL');
  setNarrator(equal?'REPLAY VERIFIED · ALL 100 TRAJECTORIES IDENTICAL':'REPLAY FAILED · TRAJECTORIES DIVERGED');
}
var running=false,tick=0,state={x:0,y:0,z:0},auditLog=[];
function startRun(){clearLogs();running=true;tick=0;state={x:0,y:0,z:0};auditLog=[];setNarrator('RUNNING · SUBSTRATE ADVANCING');runTick();}
function runTick(){
  if(!running)return;
  var b=clamp(state),c=generateCandidates(b,tick),n=collapse(c,b);
  var entry={tick:tick,state:{x:state.x,y:state.y,z:state.z},next:{x:n.x,y:n.y,z:n.z}};
  auditLog.push(entry);persistEntry(entry);
  logTo('log_main','t='+tick+' state='+JSON.stringify(state)+' next='+JSON.stringify(n));
  logTo('log_audit','t='+tick+' '+JSON.stringify(entry));
  state=n;tick++;
  setTimeout(runTick,20);
}
function killRun(){if(!running){setNarrator('NO ACTIVE RUN');return;}running=false;logTo('log_main','=== HARD CRASH · EXECUTION HALTED ===');setNarrator('CRASH INJECTED · SUBSTRATE HALTED · SAFE-RETURN AVAILABLE VIA AUDIT');}
function resumeFromAudit(){loadDB(function(persisted){if(!persisted||!persisted.length){setNarrator('NO AUDIT DATA · START A RUN FIRST');return;}auditLog=persisted;var last=auditLog[auditLog.length-1];state={x:last.next.x,y:last.next.y,z:last.next.z};tick=last.tick+1;running=true;logTo('log_main','=== SAFE-RETURN · RESUMED FROM t='+last.tick+' ===');setNarrator('SAFE-RETURN · RESUMED FROM AUDIT @ t='+last.tick);runTick();});}
function runParallel(){document.getElementById('log_parallel').textContent='';if(!auditLog.length){logTo('log_parallel','No audit data.');setNarrator('PARALLEL REFERENCE · NO DATA');return;}var ps={x:0,y:0,z:0};for(var i=0;i<auditLog.length;i++){var t=auditLog[i].tick,b=clamp(ps),c=generateCandidates(b,t),n=collapse(c,b);logTo('log_parallel','t='+t+' '+JSON.stringify(ps)+' -> '+JSON.stringify(n));ps=n;}setNarrator('PARALLEL REFERENCE RUN COMPLETE');}
function diffRuns(){document.getElementById('log_diff').textContent='';if(!auditLog.length){logTo('log_diff','No audit data.');setNarrator('DIFF · NO AUDIT DATA');return;}var ps={x:0,y:0,z:0},identical=true;for(var i=0;i<auditLog.length;i++){var entry=auditLog[i],t=entry.tick,b=clamp(ps),c=generateCandidates(b,t),n=collapse(c,b);if(n.x!==entry.next.x||n.y!==entry.next.y||n.z!==entry.next.z){identical=false;logTo('log_diff','DIFF @ t='+t);logTo('log_diff','MAIN: '+JSON.stringify(entry.next));logTo('log_diff','REF:  '+JSON.stringify(n));break;}ps=n;}if(identical){logTo('log_diff','=== TRAJECTORIES IDENTICAL ===');setNarrator('DIFF COMPLETE · TRAJECTORIES IDENTICAL · SAFE-RETURN VERIFIED');}else{setNarrator('DIFF COMPLETE · TRAJECTORIES DIVERGED');}}
function exportAudit(){if(!auditLog.length){setNarrator('EXPORT · NO AUDIT DATA');return;}var blob=new Blob([JSON.stringify(auditLog,null,2)],{type:'application/json'});var a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='rsv2_lite_audit_log.json';a.click();URL.revokeObjectURL(a.href);setNarrator('AUDIT EXPORTED · STRUCTURED TRACE AVAILABLE FOR OFFLINE INSPECTION');}
</script>
</body>
</html>

FEATURED TOYS

Four featured tests — agent failsafe, full HEG→CAP→RS pipeline, RPU vs Transformer, and the RSv2 intent orchestration layer.

TOY·01 — RS v1 — Agent Framework Toy

Wraps a multi-agent orchestration layer (PlannerAgent, DataAgent, ActionAgent) inside an RS v1 cycle. Visualizes state → forward model → plan scoring → collapse. Includes live tool-failure injection to demonstrate RS failsafe and recovery.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>RS‑v1 + Agent Framework Toy</title>
  <style>
    body { font-family: system-ui, sans-serif; background:#05060a; color:#e9ecef; margin:0; padding:20px; }
    h1 { margin-top:0; }
    .grid { display:flex; flex-wrap:wrap; gap:16px; }
    .panel { background:#11131c; border-radius:8px; padding:12px 14px; flex:1 1 280px; min-width:280px; }
    .label { font-size:11px; text-transform:uppercase; letter-spacing:0.12em; color:#9ca3c7; }
    .value { font-size:20px; margin:4px 0 8px; }
    .tag { display:inline-block; padding:2px 6px; border-radius:4px; font-size:10px; margin-right:4px; margin-bottom:2px; }
    .tag-agent { background:#264653; color:#e9ecef; }
    .tag-rs { background:#e9c46a; color:#11131c; }
    .tag-tool { background:#2a9d8f; color:#e9ecef; }
    .tag-error { background:#e76f51; color:#fff; }
    button { margin-top:8px; padding:7px 12px; border-radius:4px; border:none; cursor:pointer; background:#4cc9f0; color:#05060a; font-weight:600; font-size:13px; }
    button:disabled { opacity:0.4; cursor:default; }
    .log { font-size:11px; max-height:220px; overflow:auto; background:#080914; padding:8px; border-radius:6px; }
    .pill { display:inline-block; padding:2px 8px; border-radius:999px; font-size:11px; margin-right:4px; }
    .pill-good { background:#2a9d8f33; color:#2a9d8f; }
    .pill-warn { background:#e9c46a33; color:#e9c46a; }
    .pill-bad { background:#e76f5133; color:#e76f51; }
    .bar-wrap { background:#1b1e2b; border-radius:4px; height:8px; overflow:hidden; margin-top:4px; }
    .bar { height:100%; background:#4cc9f0; width:0%; transition:width 0.2s ease-out; }
    code { font-size:11px; background:#11131c; padding:2px 4px; border-radius:4px; }
  </style>
<style>
/* === RS AMBER CRT THEME (injected per Style Guide) === */
:root{--amber:#ffb86c;--amber-soft:#f1a85a;--amber-dim:#c28a4a;--bg:#050302;--bg-panel:#120b06;--border:#3a2614;--danger:#ff5555;--ok:#50fa7b;}
html,body{background:var(--bg) !important;color:var(--amber) !important;font-family:"IBM Plex Mono","SF Mono",Menlo,Consolas,monospace !important;}
body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:9998;background:repeating-linear-gradient(to bottom,rgba(0,0,0,0.25) 0,rgba(0,0,0,0.25) 1px,transparent 2px,transparent 3px);mix-blend-mode:multiply;}
body::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:9999;background:radial-gradient(circle at top,rgba(255,184,108,0.16) 0%,transparent 55%);}
h1,h2,h3{color:var(--amber) !important;text-transform:uppercase;letter-spacing:0.08em;text-shadow:0 0 6px rgba(255,184,108,0.4);}
h1{font-size:1.1rem !important;} h2{font-size:0.9rem !important;color:var(--amber-soft) !important;}
p,div,span,label,td,th,li{color:var(--amber) !important;}
.panel,.card,.section,.box,.grid>div{background:radial-gradient(circle at top,#1b1008 0%,#0a0503 70%) !important;border:1px solid var(--border) !important;border-radius:8px !important;box-shadow:0 0 6px rgba(255,184,108,0.18) inset !important;}
button{background:#3a2614 !important;color:var(--amber) !important;border:1px solid var(--border) !important;border-radius:4px !important;font-family:inherit !important;text-transform:uppercase;letter-spacing:0.08em;cursor:pointer;transition:all 0.15s;}
button:hover{background:#4a311b !important;box-shadow:0 0 8px rgba(255,184,108,0.4);transform:translateY(-1px);}
button:disabled{opacity:0.4 !important;}
pre,.log,.logbox,.output,textarea,input,select,code{background:#050302 !important;color:var(--amber) !important;border:1px solid var(--border) !important;font-family:inherit !important;}
.tag,.pill,.badge{border:1px solid var(--border) !important;background:#1a0d06 !important;color:var(--amber-soft) !important;}
.bar-wrap{background:#1b1008 !important;} .bar{background:var(--amber) !important;}
a{color:var(--amber-soft) !important;}
::-webkit-scrollbar{width:8px;height:8px;} ::-webkit-scrollbar-track{background:#0a0503;} ::-webkit-scrollbar-thumb{background:#3a2614;border-radius:4px;}

</style>
</head>
<body>
  <h1>RS‑v1 + Agent Framework Toy</h1>
  <p style="max-width:760px;font-size:13px;line-height:1.5;">
    Think of this as a tiny mock of a <b>Microsoft‑style agent framework</b> on top (agents, tools, steps)
    running on a <b>reasoning substrate (RS‑v1)</b> underneath.
    The agent framework thinks in terms of <code>steps</code> and <code>tools</code>; RS thinks in terms of
    <code>state → forward model → plans → scoring → collapse</code>.
  </p>

  <div class="grid">
    <!-- RS State / Control -->
    <div class="panel">
      <div class="label">RS‑v1 Control Loop</div>
      <div class="value" id="rsMode">IDLE</div>
      <div>
        <span class="tag tag-rs">RS‑STATEFUL</span>
        <span class="tag tag-rs">FORWARD MODEL</span>
        <span class="tag tag-rs">PLANS + COLLAPSE</span>
      </div>
      <div style="margin-top:10px;font-size:12px;">
        <b>RS State:</b><br/>
        <span class="pill" id="pillProgress"></span>
        <span class="pill" id="pillError"></span>
        <span class="pill" id="pillCost"></span>
      </div>
      <button id="startBtn">Start Scenario</button>
      <button id="failBtn">Inject Tool Failures</button>
      <button id="resetBtn">Reset</button>
    </div>

    <!-- Agent Framework View -->
    <div class="panel">
      <div class="label">Agent Framework (Mock)</div>
      <div class="value" id="agentStatus">IDLE</div>
      <div style="font-size:12px;margin-bottom:6px;">
        <b>Active Agent:</b> <span id="activeAgent">—</span><br/>
        <b>Last Tool:</b> <span id="lastTool">—</span><br/>
        <b>Step:</b> <span id="stepIdx">0</span>
      </div>
      <div class="label" style="margin-top:8px;">Agent Step Progress</div>
      <div class="bar-wrap"><div class="bar" id="progressBar"></div></div>
      <div class="label" style="margin-top:8px;">Error Rate (simulated)</div>
      <div class="bar-wrap"><div class="bar" id="errorBar" style="background:#e76f51;"></div></div>
      <div class="label" style="margin-top:8px;">Cost / Token Budget (simulated)</div>
      <div class="bar-wrap"><div class="bar" id="costBar" style="background:#e9c46a;"></div></div>
    </div>

    <!-- Event Log -->
    <div class="panel">
      <div class="label">Event Log (RS + Agent)</div>
      <div class="log" id="logBox"></div>
    </div>
  </div>

  <script>
    // -----------------------------
    // Helpers
    // -----------------------------
    const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
    const lerp = (a, b, t) => a + (b - a) * t;

    function log(msg) {
      const box = document.getElementById("logBox");
      const ts = new Date().toLocaleTimeString();
      box.innerHTML = `[${ts}] ${msg}<br>` + box.innerHTML;
    }

    // -----------------------------
    // Mock "Microsoft Agent Framework"
    // -----------------------------
    const AGENTS = [
      { name: "PlannerAgent", tools: ["SearchTool", "SummarizeTool"] },
      { name: "DataAgent", tools: ["DBQueryTool", "TransformTool"] },
      { name: "ActionAgent", tools: ["APICallTool", "NotifyTool"] }
    ];

    let agentState = {
      activeAgent: null,
      stepIndex: 0,
      totalSteps: 10,
      errorRate: 0.0,
      cost: 0.0,
      progress: 0.0,
      failingTools: false
    };

    function agent_step() {
      // Simulate a single "agent framework" step: pick a tool, maybe fail, advance progress.
      if (!agentState.activeAgent) {
        agentState.activeAgent = AGENTS[0];
        log(`AgentFramework: starting with agent ${agentState.activeAgent.name}`);
      }

      const tools = agentState.activeAgent.tools;
      const tool = tools[Math.floor(Math.random() * tools.length)];
      document.getElementById("lastTool").textContent = tool;

      // Simulate cost and error
      const baseCost = 0.02;
      const extraCost = Math.random() * 0.02;
      agentState.cost = clamp(agentState.cost + baseCost + extraCost, 0, 1);

      let stepFailed = false;
      let failProb = agentState.failingTools ? 0.5 : 0.15;
      if (Math.random() < failProb) {
        stepFailed = true;
        agentState.errorRate = clamp(agentState.errorRate + 0.12, 0, 1);
        log(`AgentFramework: tool ${tool} failed.`);
      } else {
        agentState.errorRate = clamp(agentState.errorRate - 0.05, 0, 1);
      }

      if (!stepFailed) {
        agentState.stepIndex = clamp(agentState.stepIndex + 1, 0, agentState.totalSteps);
        agentState.progress = agentState.stepIndex / agentState.totalSteps;
        log(`AgentFramework: ${agentState.activeAgent.name} used ${tool}, step ${agentState.stepIndex}/${agentState.totalSteps}.`);
      }

      // Maybe switch agent (mock "planner" behavior)
      if (agentState.stepIndex === 3) agentState.activeAgent = AGENTS[1];
      if (agentState.stepIndex === 7) agentState.activeAgent = AGENTS[2];

      document.getElementById("activeAgent").textContent = agentState.activeAgent.name;
      document.getElementById("stepIdx").textContent = agentState.stepIndex;
    }

    // -----------------------------
    // RS‑v1 Substrate (Toy)
    // -----------------------------
    let rsState = {
      progress: 0.0,
      errorRate: 0.0,
      cost: 0.0,
      mode: "IDLE",
      history: []
    };

    const SWITCH_THRESHOLD = 0.12;

    function read_state() {
      return {
        progress: agentState.progress,
        errorRate: agentState.errorRate,
        cost: agentState.cost
      };
    }

    function forward_model(state) {
      // Predict near future: if we keep doing what we're doing, where do we go?
      const predicted = { ...state };
      // Errors tend to accumulate if high; cost creeps up; progress slows under high error.
      const errorDrift = state.errorRate > 0.4 ? 0.05 : -0.03;
      predicted.errorRate = clamp(state.errorRate + errorDrift, 0, 1);

      const costDrift = 0.04 + state.errorRate * 0.06;
      predicted.cost = clamp(state.cost + costDrift, 0, 1);

      const progressGain = state.errorRate > 0.5 ? 0.01 : 0.06;
      predicted.progress = clamp(state.progress + progressGain, 0, 1);

      return predicted;
    }

    function generate_plans(predicted) {
      // RS plans are "policies" over the agent framework, not direct tool calls.
      return [
        { name: "STEADY", description: "Continue current agent, normal pace." },
        { name: "BACKOFF_RETRY", description: "Slow down, reduce tool calls, focus on reliability." },
        { name: "AGENT_SWITCH", description: "Switch to a different agent profile." },
        { name: "FAIL_SAFE", description: "Stop complex actions, summarize, and exit safely." }
      ];
    }

    function score_plan(plan, predicted) {
      // Lower is better. Each non-STEADY plan carries a BASE COST (intervention overhead)
      // that is only overcome by regime-specific bonuses — so interventions trigger
      // when conditions warrant them, not by default.
      const { progress, errorRate, cost } = predicted;

      let latencyWeight = 0.9;
      let reliabilityWeight = 1.2;
      let costWeight = 1.0;
      let baseCost = 0;

      if (plan.name === "BACKOFF_RETRY") {
        latencyWeight = 0.6;
        reliabilityWeight = 1.5;
        costWeight = 0.9;
        baseCost = 0.45; // slowing down sacrifices throughput
      } else if (plan.name === "AGENT_SWITCH") {
        latencyWeight = 0.8;
        reliabilityWeight = 1.3;
        costWeight = 1.0;
        baseCost = 0.5; // switching agents has real overhead
      } else if (plan.name === "FAIL_SAFE") {
        latencyWeight = 0.4;
        reliabilityWeight = 1.8;
        costWeight = 0.7;
        baseCost = 1.5; // abandoning the task is expensive by default
      }

      const latencyCost = (1 - progress) * latencyWeight;
      const reliabilityCost = errorRate * reliabilityWeight;
      const budgetCost = cost * costWeight;

      // Regime-specific bonuses: each intervention becomes preferred in its intended regime.
      let bonus = 0;
      if (plan.name === "FAIL_SAFE" && (errorRate > 0.7 || cost > 0.85)) {
        bonus -= 1.9; // genuine emergency: fail-safe strongly preferred
      }
      if (plan.name === "BACKOFF_RETRY" && errorRate > 0.35 && errorRate <= 0.5) {
        bonus -= 0.55; // moderate error regime: back off
      }
      if (plan.name === "AGENT_SWITCH" && errorRate > 0.5 && errorRate <= 0.7) {
        bonus -= 0.75; // persistent/stuck error regime: switch agents
      }

      return latencyCost + reliabilityCost + budgetCost + baseCost + bonus;
    }

    function score_plans(plans, predicted) {
      return plans.map(p => ({ plan: p, energy: score_plan(p, predicted) }))
                  .sort((a, b) => a.energy - b.energy);
    }

    function collapse(scored, previousPlan) {
      const best = scored[0];
      if (!previousPlan) return best.plan;

      const prevEntry = scored.find(x => x.plan.name === previousPlan.name) || best;
      const gap = best.energy - prevEntry.energy;

      if (gap < -SWITCH_THRESHOLD) return best.plan;
      return previousPlan;
    }

    function apply_plan(plan) {
      // RS doesn't call tools directly; it governs the agent framework.
      if (plan.name === "STEADY") {
        rsState.mode = "STEADY";
        // normal behavior
      } else if (plan.name === "BACKOFF_RETRY") {
        rsState.mode = "BACKOFF_RETRY";
        // reduce failure impact: lower failure probability by disabling injected failures
        agentState.failingTools = false;
      } else if (plan.name === "AGENT_SWITCH") {
        rsState.mode = "AGENT_SWITCH";
        // pick the agent with least "stress" (toy: just cycle)
        const idx = AGENTS.indexOf(agentState.activeAgent);
        agentState.activeAgent = AGENTS[(idx + 1) % AGENTS.length];
        log(`RS: switching to agent ${agentState.activeAgent.name} to reduce stress.`);
      } else if (plan.name === "FAIL_SAFE") {
        rsState.mode = "FAIL_SAFE";
        // stop complex actions, simulate "summarize and exit"
        log("RS: entering FAIL‑SAFE mode → summarizing and exiting gracefully.");
        running = false;
      }
      log(`RS: applied plan ${plan.name}.`);
    }

    // -----------------------------
    // Loop + UI
    // -----------------------------
    let running = false;
    let previousPlan = null;

    const rsModeEl = document.getElementById("rsMode");
    const agentStatusEl = document.getElementById("agentStatus");
    const progressBar = document.getElementById("progressBar");
    const errorBar = document.getElementById("errorBar");
    const costBar = document.getElementById("costBar");
    const pillProgress = document.getElementById("pillProgress");
    const pillError = document.getElementById("pillError");
    const pillCost = document.getElementById("pillCost");

    function render() {
      rsModeEl.textContent = rsState.mode;
      agentStatusEl.textContent = running ? "RUNNING" : "STOPPED";

      progressBar.style.width = Math.round(agentState.progress * 100) + "%";
      errorBar.style.width = Math.round(agentState.errorRate * 100) + "%";
      costBar.style.width = Math.round(agentState.cost * 100) + "%";

      pillProgress.textContent = `Progress ${Math.round(agentState.progress * 100)}%`;
      pillError.textContent = `Error ${(agentState.errorRate * 100).toFixed(0)}%`;
      pillCost.textContent = `Cost ${(agentState.cost * 100).toFixed(0)}%`;

      pillProgress.className = "pill " + (agentState.progress > 0.7 ? "pill-good" : "pill-warn");
      pillError.className = "pill " + (agentState.errorRate > 0.5 ? "pill-bad" : (agentState.errorRate > 0.2 ? "pill-warn" : "pill-good"));
      pillCost.className = "pill " + (agentState.cost > 0.8 ? "pill-bad" : (agentState.cost > 0.5 ? "pill-warn" : "pill-good"));
    }

    function tick() {
      if (!running) return;

      // 1) Agent framework takes a step (what they already have)
      agent_step();

      // 2) RS reads state
      const s = read_state();
      rsState.progress = s.progress;
      rsState.errorRate = s.errorRate;
      rsState.cost = s.cost;

      // 3) RS forward model
      const predicted = forward_model(s);

      // 4) RS generates and scores plans
      const plans = generate_plans(predicted);
      const scored = score_plans(plans, predicted);

      // 5) RS collapses to a single plan
      const chosen = collapse(scored, previousPlan);
      previousPlan = chosen;

      // 6) RS applies plan (governs the agent framework)
      apply_plan(chosen);

      render();

      if (running) setTimeout(tick, 500);
    }

    // -----------------------------
    // Controls
    // -----------------------------
    document.getElementById("startBtn").onclick = () => {
      if (running) return;
      running = true;
      rsState.mode = "STEADY";
      log("Scenario started. Agent framework is running under RS‑v1 control.");
      tick();
    };

    document.getElementById("failBtn").onclick = () => {
      agentState.failingTools = true;
      log("Injected high tool failure regime (simulated). RS should back off / switch / fail‑safe.");
    };

    document.getElementById("resetBtn").onclick = () => {
      running = false;
      previousPlan = null;
      agentState = {
        activeAgent: null,
        stepIndex: 0,
        totalSteps: 10,
        errorRate: 0.0,
        cost: 0.0,
        progress: 0.0,
        failingTools: false
      };
      rsState = {
        progress: 0.0,
        errorRate: 0.0,
        cost: 0.0,
        mode: "IDLE",
        history: []
      };
      document.getElementById("activeAgent").textContent = "—";
      document.getElementById("lastTool").textContent = "—";
      document.getElementById("stepIdx").textContent = "0";
      log("Reset scenario.");
      render();
    };

    render();
  </script>
</body>
</html>

TOY·02 — HEG — CAP — RS Pipeline

Full HEG→CAP→RS pipeline. Choose text, audio, or video presets and watch each expression processed through SEGMENT, ACT, TARGET, EMOTION, PATTERN, and CAP_BUILD into a typed Cognitive Action Packet. Includes audit envelopes and replay/diff.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>HEG Toy – Stable Version</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600;700&display=swap');
    :root{--amber:#ffb86c;--amber-soft:#f1a85a;--amber-dim:#c28a4a;--bg:#050302;--border:#3a2614;--danger:#ff5555;--ok:#50fa7b;}
    *{box-sizing:border-box;}
    body{margin:0;padding:0;font-family:"IBM Plex Mono","SF Mono",Menlo,monospace;background:radial-gradient(circle at top,#1a0f07 0,#050302 55%);color:var(--amber);text-shadow:0 0 4px rgba(255,184,108,0.6);overflow-y:auto;min-height:100vh;font-size:0.82rem;line-height:1.65;}
    body::before{content:"";position:fixed;inset:0;pointer-events:none;background:repeating-linear-gradient(to bottom,rgba(255,255,255,0.04),rgba(255,255,255,0.04) 1px,transparent 1px,transparent 3px);mix-blend-mode:soft-light;opacity:0.35;z-index:999;}
    body::after{content:"";position:fixed;inset:0;pointer-events:none;background:radial-gradient(circle at center,rgba(255,184,108,0.18),transparent 60%);mix-blend-mode:screen;opacity:0.7;z-index:998;}
    header{padding:0.75rem 1.5rem;border-bottom:1px solid var(--border);background:linear-gradient(to bottom,#1b1008,#0a0503);display:flex;align-items:center;justify-content:space-between;}
    h1{margin:0;font-size:0.95rem;letter-spacing:0.12em;text-transform:uppercase;color:var(--amber);}
    h2{margin:0 0 0.5rem;font-size:0.82rem;text-transform:uppercase;letter-spacing:0.14em;color:var(--amber-soft);}
    h3{font-size:0.78rem;letter-spacing:0.1em;text-transform:uppercase;color:var(--amber-dim);margin:0 0 0.4rem;}
    .header-right{font-size:0.7rem;opacity:0.8;}
    main{padding:0.75rem 1rem;}
    section{background:radial-gradient(circle at top,#1b1008 0,#0a0503 70%);border:1px solid var(--border);border-radius:8px;padding:0.75rem 1rem;position:relative;overflow:hidden;margin-bottom:0.75rem;}
    section::before{content:"";position:absolute;inset:0;border-radius:inherit;border:1px solid rgba(255,184,108,0.08);pointer-events:none;}
    label{font-size:0.75rem;display:block;margin-bottom:0.3rem;letter-spacing:0.06em;}
    input,select,textarea{width:100%;padding:0.35rem 0.5rem;border-radius:4px;border:1px solid var(--border);background:#050302;color:var(--amber);font-family:inherit;font-size:0.8rem;outline:none;box-shadow:0 0 6px rgba(255,184,108,0.15) inset;margin-bottom:0.4rem;}
    button{background:#1a0d06;color:var(--amber);border:1px solid var(--border);padding:0.35rem 0.75rem;margin:3px 4px 3px 0;cursor:pointer;border-radius:4px;font-family:inherit;font-size:0.78rem;letter-spacing:0.08em;text-transform:uppercase;transition:background 0.15s,box-shadow 0.15s,transform 0.05s;}
    button:hover{background:#2a1a0a;border-color:var(--amber);box-shadow:0 0 8px rgba(255,184,108,0.3);transform:translateY(-1px);}
    pre,.log-box{background:#050302;border:1px solid var(--border);border-radius:4px;padding:0.6rem 0.75rem;max-height:320px;overflow-y:auto;font-size:0.76rem;color:var(--amber);white-space:pre-wrap;word-break:break-word;line-height:1.55;}
    table{border-collapse:collapse;width:100%;margin-top:0.5rem;}
    th{color:var(--amber-soft);border-bottom:1px solid var(--border);padding:4px 8px;text-align:left;font-size:0.74rem;letter-spacing:0.08em;}
    td{color:var(--amber);border-bottom:1px solid #1a1209;padding:4px 8px;font-size:0.76rem;}
    .badge{display:inline-block;font-size:0.64rem;letter-spacing:0.1em;padding:0.12rem 0.45rem;border:1px solid var(--border);border-radius:2px;margin-right:4px;}
    .small{font-size:0.76rem;opacity:0.72;line-height:1.55;}
    ::-webkit-scrollbar{width:5px;}
    ::-webkit-scrollbar-track{background:#050302;}
    ::-webkit-scrollbar-thumb{background:#3a2614;border-radius:3px;}
    ::-webkit-scrollbar-thumb:hover{background:#4a311b;}
</style>
<style>
/* === RS AMBER CRT THEME (injected per Style Guide) === */
:root{--amber:#ffb86c;--amber-soft:#f1a85a;--amber-dim:#c28a4a;--bg:#050302;--bg-panel:#120b06;--border:#3a2614;--danger:#ff5555;--ok:#50fa7b;}
html,body{background:var(--bg) !important;color:var(--amber) !important;font-family:"IBM Plex Mono","SF Mono",Menlo,Consolas,monospace !important;}
body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:9998;background:repeating-linear-gradient(to bottom,rgba(0,0,0,0.25) 0,rgba(0,0,0,0.25) 1px,transparent 2px,transparent 3px);mix-blend-mode:multiply;}
body::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:9999;background:radial-gradient(circle at top,rgba(255,184,108,0.16) 0%,transparent 55%);}
h1,h2,h3{color:var(--amber) !important;text-transform:uppercase;letter-spacing:0.08em;text-shadow:0 0 6px rgba(255,184,108,0.4);}
h1{font-size:1.1rem !important;} h2{font-size:0.9rem !important;color:var(--amber-soft) !important;}
p,div,span,label,td,th,li{color:var(--amber) !important;}
.panel,.card,.section,.box,.grid>div{background:radial-gradient(circle at top,#1b1008 0%,#0a0503 70%) !important;border:1px solid var(--border) !important;border-radius:8px !important;box-shadow:0 0 6px rgba(255,184,108,0.18) inset !important;}
button{background:#3a2614 !important;color:var(--amber) !important;border:1px solid var(--border) !important;border-radius:4px !important;font-family:inherit !important;text-transform:uppercase;letter-spacing:0.08em;cursor:pointer;transition:all 0.15s;}
button:hover{background:#4a311b !important;box-shadow:0 0 8px rgba(255,184,108,0.4);transform:translateY(-1px);}
button:disabled{opacity:0.4 !important;}
pre,.log,.logbox,.output,textarea,input,select,code{background:#050302 !important;color:var(--amber) !important;border:1px solid var(--border) !important;font-family:inherit !important;}
.tag,.pill,.badge{border:1px solid var(--border) !important;background:#1a0d06 !important;color:var(--amber-soft) !important;}
.bar-wrap{background:#1b1008 !important;} .bar{background:var(--amber) !important;}
a{color:var(--amber-soft) !important;}
::-webkit-scrollbar{width:8px;height:8px;} ::-webkit-scrollbar-track{background:#0a0503;} ::-webkit-scrollbar-thumb{background:#3a2614;border-radius:4px;}

</style>
</head>
<body>
<header>
  <h1>HEG Toy – Stable Version</h1>
  <span class="header-right">HEG MODULE // AMBER TERMINAL</span>
</header>
<main>
<section>
<div class="app-container">

  <!-- LEFT: Input + Trace -->
  <div class="pane left-pane">
    <div class="static-panel">
      <div class="static-header">HEG Toy – Input & Trace</div>
      <div class="static-label">
        Toy HEG → CAP → RS pipeline. Structure only, not real substrate.
      </div>

      <textarea id="inputText" placeholder="Example:
Okay, I’m frustrated, but here’s what I want:
First, help me outline a plan.
Then tell me if there are any obvious risks I’m missing."></textarea>

      <div class="section-title">Presets</div>
      <button class="preset-btn" data-preset="textFrustrated">Text: Frustrated Plan + Risks</button>
      <button class="preset-btn" data-preset="audioFrustrated">Audio: Frustrated, Fast</button>
      <button class="preset-btn" data-preset="videoPointing">Video: Pointing, Forward</button>

      <div class="section-title">Run</div>
      <button id="runButton">Run HEG</button>
      <button id="replayFromCapsButton">Replay from CAPs</button>
      <button id="replayFromRawButton">Replay from Raw Input</button>

      <div class="static-label" id="modeLabel">Current modality: text</div>
    </div>

    <div class="dynamic-panel" id="traceArea"></div>
  </div>

  <!-- RIGHT: Scoring + CAPs + RS + Audit + Replay -->
  <div class="pane right-pane">
    <div class="static-panel">
      <div class="static-header">Scoring, CAPs, RS, Audit</div>
      <div id="scoringBlock" class="scoring-block">
        Run HEG to see scoring explanation.
      </div>
      <div id="showMore" class="show-more">Show More…</div>
    </div>

    <div class="dynamic-panel" id="rightDynamic">
      <div class="section-title">Cognitive Action Packets (CAPs)</div>
      <div id="capsContainer"></div>

      <div class="section-title">Toy Reasoning Substrate (RS) State</div>
      <div id="rsState" class="rs-state"></div>

      <div class="section-title">Audit Envelopes</div>
      <div class="small-note">
        Each envelope summarizes one CAP. Click to expand. RS can audit from CAPs; HEG audit is diagnostic.
      </div>
      <div id="auditEnvelopes"></div>

      <div class="section-title">Replay / Diff Output</div>
      <div id="replayOutput" class="rs-state">
        Replay output will appear here.
      </div>
    </div>
  </div>

</div>

<script>
  // PRESETS
  const PRESETS = {
    textFrustrated: {
      mode: "text",
      text: `Okay, I’m frustrated, but here’s what I want:
First, help me outline a plan.
Then tell me if there are any obvious risks I’m missing.`
    },
    audioFrustrated: {
      mode: "audio",
      text: "[AUDIO] Frustrated tone, fast speech, high emphasis."
    },
    videoPointing: {
      mode: "video",
      text: "[VIDEO] User pointing at screen, leaning forward, medium intensity."
    }
  };

  // GLOBAL STATE
  let currentMode = "text";
  let lastRawInput = "";
  let lastMode = "text";
  let lastCaps = [];
  let lastRSState = null;

  let auditLog = [];
  let replayLog = [];
  let auditEnvelopes = [];

  // DOM
  const inputTextEl = document.getElementById("inputText");
  const runButtonEl = document.getElementById("runButton");
  const replayFromCapsButtonEl = document.getElementById("replayFromCapsButton");
  const replayFromRawButtonEl = document.getElementById("replayFromRawButton");
  const traceAreaEl = document.getElementById("traceArea");
  const capsContainerEl = document.getElementById("capsContainer");
  const rsStateEl = document.getElementById("rsState");
  const replayOutputEl = document.getElementById("replayOutput");
  const scoringBlockEl = document.getElementById("scoringBlock");
  const showMoreEl = document.getElementById("showMore");
  const auditEnvelopesEl = document.getElementById("auditEnvelopes");
  const presetButtons = document.querySelectorAll(".preset-btn");
  const modeLabelEl = document.getElementById("modeLabel");

  // UTILS
  function appendTraceLine(text) {
    const line = document.createElement("div");
    line.className = "trace-line";
    line.textContent = text;
    traceAreaEl.appendChild(line);
    traceAreaEl.scrollTop = traceAreaEl.scrollHeight;
  }

  function clearDynamicUI() {
    traceAreaEl.innerHTML = "";
    capsContainerEl.innerHTML = "";
    rsStateEl.textContent = "";
    replayOutputEl.textContent = "Replay output will appear here.";
    scoringBlockEl.textContent = "Run HEG to see scoring explanation.";
    scoringBlockEl.classList.remove("expanded");
    showMoreEl.textContent = "Show More…";
    auditEnvelopesEl.innerHTML = "";
  }

  // HEG OPERATORS
  function segment(text) {
    const rawSegments = text
      .split(/[\n]+/)
      .map(line => line.trim())
      .filter(line => line.length > 0)
      .flatMap(line => line.split(/(?<=[.?!])\s+/));

    const segments = rawSegments
      .map(s => s.trim())
      .filter(s => s.length > 0);

    auditLog.push({ operator: "SEGMENT", input: text, output: segments });
    return segments;
  }

  function classifyAct(segment, actHint) {
    const s = segment.trim().toLowerCase();
    let act = null;

    if (actHint) act = actHint;
    else if (segment.endsWith("?")) act = "ASK";
    else if (
      s.startsWith("please ") ||
      s.startsWith("can you ") ||
      s.startsWith("help me ") ||
      s.startsWith("first, ") ||
      s.startsWith("then ")
    ) act = "COMMAND";
    else if (
      s.includes("i’m frustrated") ||
      s.includes("i am frustrated") ||
      s.includes("here's what i want")
    ) act = "META";
    else act = "ASSERT";

    auditLog.push({ operator: "ACT", input: segment, output: act });
    return act;
  }

  function mapTargets(segment, actType, targetHint) {
    const lower = segment.toLowerCase();
    const targets = [];
    function add(type, c) { targets.push({ type, confidence: c }); }

    if (targetHint) {
      add(targetHint, 0.95);
    } else {
      if (lower.includes("plan")) add("PLAN", 0.92);
      if (lower.includes("goal")) add("GOAL", 0.90);
      if (lower.includes("risk")) add("CONSTRAINT", 0.90);
      if (lower.includes("i think") || lower.includes("maybe")) add("HYPOTHESIS", 0.85);
      if (actType === "META") add("MODE", 0.80);
    }

    if (targets.length === 0) add("UNKNOWN", 0.50);

    auditLog.push({ operator: "TARGET", input: segment, output: targets });
    return targets;
  }

  function extractEmotion(segment) {
    const lower = segment.toLowerCase();
    let valence = 0, arousal = 0;

    if (lower.includes("frustrated")) { valence -= 0.4; arousal += 0.3; }
    if (segment.includes("!")) arousal += 0.3;

    valence = Math.max(-1, Math.min(1, valence));
    arousal = Math.max(0, Math.min(1, arousal));

    const e = { valence, arousal };
    auditLog.push({ operator: "EMOTION", input: segment, output: e });
    return e;
  }

  function detectArgumentPattern(segment) {
    const lower = segment.toLowerCase();
    let p = "NONE";
    if (lower.includes("everyone knows")) p = "APPEAL_POPULARITY";
    auditLog.push({ operator: "PATTERN", input: segment, output: p });
    return p;
  }

  // MULTIMODAL (SIMULATED)
  function extractAudioFeatures(text) {
    let valence = 0, arousal = 0, actHint = null;
    const lower = text.toLowerCase();
    if (lower.includes("frustrated")) { valence -= 0.5; arousal += 0.5; actHint = "META"; }
    if (lower.includes("fast")) arousal += 0.3;
    const f = { valence, arousal, actHint };
    auditLog.push({ operator: "AUDIO_FEATURES", input: text, output: f });
    return f;
  }

  function extractVideoFeatures(text) {
    let actHint = null, targetHint = null, arousalDelta = 0;
    const lower = text.toLowerCase();
    if (lower.includes("pointing")) { actHint = "COMMAND"; targetHint = "PLAN"; }
    if (lower.includes("leaning forward")) arousalDelta += 0.3;
    const f = { actHint, targetHint, arousalDelta };
    auditLog.push({ operator: "VIDEO_FEATURES", input: text, output: f });
    return f;
  }

  // CAP BUILDER
  function buildCAP(segment, act, targets, emotion, pattern, modality) {
    const maxC = targets.reduce((m, t) => Math.max(m, t.confidence), 0);
    const cap = {
      modality,
      act,
      targets,
      emotion,
      pattern,
      payload: segment,
      metadata: { id: Math.random().toString(16).slice(2, 10) },
      confidence: maxC
    };
    auditLog.push({ operator: "CAP", input: segment, output: cap });
    return cap;
  }

  // TOY RS
  function createEmptyRSState() {
    return { goals: [], constraints: [], hypotheses: [], actions: [], lastAction: null };
  }

  function toyRS(caps, logTarget) {
    const state = createEmptyRSState();

    caps.forEach(cap => {
      cap.targets.forEach(t => {
        let transition = null;
        switch (t.type) {
          case "PLAN":
            state.goals.push("build plan");
            state.actions.push("outline plan");
            state.lastAction = "outline plan";
            transition = "goals += ['build plan'], actions += ['outline plan']";
            break;
          case "GOAL":
            state.goals.push(cap.payload);
            state.lastAction = "register goal";
            transition = "goals += [payload]";
            break;
          case "CONSTRAINT":
            state.constraints.push(cap.payload);
            state.lastAction = "analyze constraint";
            transition = "constraints += [payload]";
            break;
          case "HYPOTHESIS":
            state.hypotheses.push(cap.payload);
            state.lastAction = "record hypothesis";
            transition = "hypotheses += [payload]";
            break;
          case "MODE":
            state.actions.push("adjust mode: meta");
            state.lastAction = "adjust mode: meta";
            transition = "actions += ['adjust mode: meta']";
            break;
        }
        if (transition && logTarget) {
          logTarget.push({ operator: "RS_TRANSITION", input: cap, output: transition });
        }
      });
    });

    return state;
  }

  // SCORING EXPLANATION
  function buildScoringExplanation(segments, caps, rsState) {
    if (!caps.length) return "Run HEG to see scoring.";

    const lines = [];
    lines.push("HEG SCORING EXPLANATION");
    lines.push("------------------------");
    lines.push("Scores are fixed-point structural weights, not probabilities.");
    lines.push("They determine which CAPs dominate when multiple targets compete.");
    lines.push("PLAN=0.92, GOAL=0.90, CONSTRAINT=0.90, HYPOTHESIS=0.85, MODE=0.80, UNKNOWN=0.50.");
    lines.push("");

    segments.forEach((seg, i) => {
      const cap = caps[i];
      if (!cap) return;
      lines.push("Segment #" + (i + 1) + " (" + cap.modality + "): " + seg);
      lines.push("  Act: " + cap.act);
      lines.push("  Targets: " + cap.targets.map(t => t.type + "(" + t.confidence + ")").join(", "));
      lines.push("  CAP.confidence = " + cap.confidence);
      lines.push("");
    });

    lines.push("RS STATE SUMMARY (toy):");
    lines.push("  Goals: " + JSON.stringify(rsState.goals));
    lines.push("  Constraints: " + JSON.stringify(rsState.constraints));
    lines.push("  Hypotheses: " + JSON.stringify(rsState.hypotheses));
    lines.push("  Actions: " + JSON.stringify(rsState.actions));
    lines.push("  Last Action: " + JSON.stringify(rsState.lastAction));

    return lines.join("\n");
  }

  // AUDIT ENVELOPES
  function buildAuditEnvelopes(caps) {
    auditEnvelopes = caps.map((cap, index) => ({
      index,
      cap,
      summary: {
        act: cap.act,
        targets: cap.targets,
        confidence: cap.confidence,
        emotion: cap.emotion,
        pattern: cap.pattern,
        modality: cap.modality,
        payload: cap.payload
      }
    }));
  }

  function renderAuditEnvelopes() {
    auditEnvelopesEl.innerHTML = "";
    if (!auditEnvelopes.length) {
      const div = document.createElement("div");
      div.className = "small-note";
      div.textContent = "No audit envelopes yet. Run HEG.";
      auditEnvelopesEl.appendChild(div);
      return;
    }

    auditEnvelopes.forEach(env => {
      const wrapper = document.createElement("div");
      wrapper.className = "audit-envelope";
      wrapper.textContent =
        "[Envelope #" + (env.index + 1) + "] " +
        env.summary.modality.toUpperCase() +
        " | Act=" + env.summary.act +
        " | Targets=" + env.summary.targets.map(t => t.type).join(", ") +
        " | Conf=" + env.summary.confidence.toFixed(2);

      const details = document.createElement("div");
      details.className = "audit-envelope-details";

      const lines = [];
      lines.push("Payload: " + env.summary.payload);
      lines.push("Emotion: valence=" + env.summary.emotion.valence.toFixed(2) +
        ", arousal=" + env.summary.emotion.arousal.toFixed(2));
      lines.push("Pattern: " + env.summary.pattern);
      lines.push("");
      lines.push("Replay from CAPs or Raw Input to demonstrate deterministic re-execution.");
      details.textContent = lines.join("\n");

      wrapper.appendChild(details);

      wrapper.addEventListener("click", () => {
        details.style.display = details.style.display === "none" ? "block" : "none";
      });

      auditEnvelopesEl.appendChild(wrapper);
    });
  }

  // RENDER HELPERS
  function renderCAP(cap) {
    const card = document.createElement("div");
    card.className = "cap-card";
    card.textContent = JSON.stringify(cap, null, 2);
    capsContainerEl.appendChild(card);
  }

  function renderRSState(state) {
    const lines = [];
    lines.push("RS STATE (toy)");
    lines.push("--------------");
    lines.push("Goals: " + JSON.stringify(state.goals));
    lines.push("Constraints: " + JSON.stringify(state.constraints));
    lines.push("Hypotheses: " + JSON.stringify(state.hypotheses));
    lines.push("Actions: " + JSON.stringify(state.actions));
    lines.push("Last Action: " + JSON.stringify(state.lastAction));
    rsStateEl.textContent = lines.join("\n");
  }

  function buildDiffView(originalCaps, replayCaps, originalRS, replayRS) {
    if (!originalCaps || !replayCaps) return "No diff available.";
    const capsEqual = JSON.stringify(originalCaps) === JSON.stringify(replayCaps);
    const rsEqual = JSON.stringify(originalRS) === JSON.stringify(replayRS);

    const lines = [];
    lines.push("CAPs equal: " + capsEqual);
    lines.push("RS state equal: " + rsEqual);
    lines.push("");

    if (!capsEqual) lines.push("CAPs differ. This would indicate nondeterminism or a bug.");
    if (!rsEqual) lines.push("RS states differ. This would indicate nondeterminism or a bug.");
    if (capsEqual && rsEqual) lines.push("Replay is identical. Deterministic audit + replay from CAPs demonstrated.");

    return lines.join("\n");
  }

  // CORE HEG RUN
  function runHEGInternal(text, mode, logTarget) {
    const localAudit = logTarget || auditLog;
    const segments = mode === "text" ? segment(text) : [text];
    const caps = [];

    let audioFeatures = null;
    let videoFeatures = null;

    if (mode === "audio") audioFeatures = extractAudioFeatures(text);
    if (mode === "video") videoFeatures = extractVideoFeatures(text);

    segments.forEach((seg, index) => {
      appendTraceLine("");
      appendTraceLine("[SEGMENT #" + (index + 1) + "][" + mode.toUpperCase() + "] " + seg);

      let actHint = null;
      let targetHint = null;
      let emotion = { valence: 0, arousal: 0 };

      if (mode === "audio" && audioFeatures) {
        actHint = audioFeatures.actHint;
        emotion = { valence: audioFeatures.valence, arousal: audioFeatures.arousal };
      } else if (mode === "video" && videoFeatures) {
        actHint = videoFeatures.actHint;
        targetHint = videoFeatures.targetHint;
        emotion = { valence: 0, arousal: Math.max(0, Math.min(1, videoFeatures.arousalDelta)) };
      }

      const act = classifyAct(seg, actHint);
      appendTraceLine("  [ACT] → " + act);

      const targets = mapTargets(seg, act, targetHint);
      appendTraceLine("  [TARGET] → " + JSON.stringify(targets));

      if (mode === "text") {
        emotion = extractEmotion(seg);
      } else {
        localAudit.push({
          operator: "EMOTION_FROM_MODALITY",
          input: { segment: seg, mode },
          output: emotion
        });
      }

      appendTraceLine(
        "  [EMOTION] → valence=" + emotion.valence.toFixed(2) +
        ", arousal=" + emotion.arousal.toFixed(2)
      );

      const pattern = detectArgumentPattern(seg);
      appendTraceLine("  [ARGPATTERN] → " + pattern);

      const cap = buildCAP(seg, act, targets, emotion, pattern, mode);
      appendTraceLine("  [CAP] → " + JSON.stringify(cap));
      caps.push(cap);

      if (!logTarget) renderCAP(cap);
    });

    return caps;
  }

  function runHEG() {
    clearDynamicUI();
    auditLog = [];
    replayLog = [];
    auditEnvelopes = [];

    const text = inputTextEl.value.trim();
    if (!text) {
      appendTraceLine("[ERROR] No input text.");
      return;
    }

    lastRawInput = text;
    lastMode = currentMode;

    appendTraceLine("[INPUT][" + currentMode.toUpperCase() + "] " + text);

    const caps = runHEGInternal(text, currentMode, auditLog);
    const rsState = toyRS(caps, auditLog);

    lastCaps = caps;
    lastRSState = rsState;

    appendTraceLine("");
    appendTraceLine("[RS] Updated state from CAP bundle.");
    renderRSState(rsState);

    const segments = currentMode === "text" ? segment(text) : [text];
    scoringBlockEl.textContent = buildScoringExplanation(segments, caps, rsState);

    buildAuditEnvelopes(caps);
    renderAuditEnvelopes();
  }

  // REPLAY
  function replayFromCaps() {
    replayLog = [];
    replayLog.push({ operator: "REPLAY_START", input: "CAP_BUNDLE" });

    if (!lastCaps.length) {
      replayOutputEl.textContent = "No CAPs to replay. Run HEG first.";
      return;
    }

    const replayRS = toyRS(lastCaps, replayLog);
    replayLog.push({ operator: "REPLAY_END", output: replayRS });

    replayOutputEl.textContent = buildDiffView(lastCaps, lastCaps, lastRSState, replayRS);
  }

  function replayFromRaw() {
    replayLog = [];
    replayLog.push({ operator: "REPLAY_START", input: "RAW_INPUT" });

    if (!lastRawInput) {
      replayOutputEl.textContent = "No raw input to replay. Run HEG first.";
      return;
    }

    const localAudit = [];
    const replayCaps = runHEGInternal(lastRawInput, lastMode, localAudit);
    const replayRS = toyRS(replayCaps, localAudit);

    replayLog = replayLog.concat(localAudit);
    replayLog.push({ operator: "REPLAY_END", output: replayRS });

    replayOutputEl.textContent = buildDiffView(lastCaps, replayCaps, lastRSState, replayRS);
  }

  // EVENTS
  runButtonEl.addEventListener("click", runHEG);
  replayFromCapsButtonEl.addEventListener("click", replayFromCaps);
  replayFromRawButtonEl.addEventListener("click", replayFromRaw);

  presetButtons.forEach(btn => {
    btn.addEventListener("click", () => {
      const key = btn.getAttribute("data-preset");
      const preset = PRESETS[key];
      if (!preset) return;
      currentMode = preset.mode;
      modeLabelEl.textContent = "Current modality: " + currentMode;
      inputTextEl.value = preset.text;
    });
  });

  showMoreEl.addEventListener("click", () => {
    if (scoringBlockEl.classList.contains("expanded")) {
      scoringBlockEl.classList.remove("expanded");
      showMoreEl.textContent = "Show More…";
    } else {
      scoringBlockEl.classList.add("expanded");
      showMoreEl.textContent = "Show Less";
    }
  });
</script>
</section>
</main>
</body>
</html>

TOY·03 — RPU vs Transformer — Stability Harness

Side-by-side: Transformer thrashes on complex input, RPU-Classic converges to a fixed point, RPU-Quantum descends an energy landscape. Canvas animations show live energy, state variance, and convergence metrics across all three engines.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html>
<head>
<title>RPU Internal Dynamics Harness</title>
<style>
body { font-family: Arial; background:#111; color:#eee; margin:20px; }
h1 { color:#6cf; }
h2 { margin-bottom:4px; }
p.subtitle { color:#aaa; margin-top:0; font-size:0.9em; }
.container { display:flex; gap:20px; margin-top:20px; }
.panel { background:#222; padding:15px; border-radius:8px; width:32%; }
button { padding:8px 12px; margin:5px; border:none; border-radius:4px; cursor:pointer; }
.run { background:#4caf50; color:white; }
.reset { background:#f44336; color:white; }
.output { background:#000; color:#0f0; padding:10px; height:200px; overflow:auto; font-family:monospace; }
.header { display:flex; justify-content:space-between; align-items:center; }
.canvas-box { background:#000; border:1px solid #333; margin-top:10px; }
.engine-sub { color:#aaa; font-size:0.8em; margin-top:-6px; margin-bottom:8px; }
</style>
<style>
/* === RS AMBER CRT THEME (injected per Style Guide) === */
:root{--amber:#ffb86c;--amber-soft:#f1a85a;--amber-dim:#c28a4a;--bg:#050302;--bg-panel:#120b06;--border:#3a2614;--danger:#ff5555;--ok:#50fa7b;}
html,body{background:var(--bg) !important;color:var(--amber) !important;font-family:"IBM Plex Mono","SF Mono",Menlo,Consolas,monospace !important;}
body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:9998;background:repeating-linear-gradient(to bottom,rgba(0,0,0,0.25) 0,rgba(0,0,0,0.25) 1px,transparent 2px,transparent 3px);mix-blend-mode:multiply;}
body::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:9999;background:radial-gradient(circle at top,rgba(255,184,108,0.16) 0%,transparent 55%);}
h1,h2,h3{color:var(--amber) !important;text-transform:uppercase;letter-spacing:0.08em;text-shadow:0 0 6px rgba(255,184,108,0.4);}
h1{font-size:1.1rem !important;} h2{font-size:0.9rem !important;color:var(--amber-soft) !important;}
p,div,span,label,td,th,li{color:var(--amber) !important;}
.panel,.card,.section,.box,.grid>div{background:radial-gradient(circle at top,#1b1008 0%,#0a0503 70%) !important;border:1px solid var(--border) !important;border-radius:8px !important;box-shadow:0 0 6px rgba(255,184,108,0.18) inset !important;}
button{background:#3a2614 !important;color:var(--amber) !important;border:1px solid var(--border) !important;border-radius:4px !important;font-family:inherit !important;text-transform:uppercase;letter-spacing:0.08em;cursor:pointer;transition:all 0.15s;}
button:hover{background:#4a311b !important;box-shadow:0 0 8px rgba(255,184,108,0.4);transform:translateY(-1px);}
button:disabled{opacity:0.4 !important;}
pre,.log,.logbox,.output,textarea,input,select,code{background:#050302 !important;color:var(--amber) !important;border:1px solid var(--border) !important;font-family:inherit !important;}
.tag,.pill,.badge{border:1px solid var(--border) !important;background:#1a0d06 !important;color:var(--amber-soft) !important;}
.bar-wrap{background:#1b1008 !important;} .bar{background:var(--amber) !important;}
a{color:var(--amber-soft) !important;}
::-webkit-scrollbar{width:8px;height:8px;} ::-webkit-scrollbar-track{background:#0a0503;} ::-webkit-scrollbar-thumb{background:#3a2614;border-radius:4px;}

</style>
</head>

<body>

<h1>RPU Internal Dynamics Harness</h1>
<p class="subtitle">
Internal Dynamics Test — Shows how each engine behaves when iterating on its own state.
Transformer thrashes. Classic converges. Quantum descends energy.
</p>

<div class="header">
    <div>
        <button class="run" onclick="runAll()">Run All</button>
        <button class="reset" onclick="resetAll()">Reset All</button>
    </div>
</div>

<div class="container">

    <!-- Transformer Simulation -->
    <div class="panel">
        <h2>Transformer</h2>
        <div class="engine-sub">Shared Context Model (Fragile)</div>
        <button class="run" onclick="runTransformer()">Run</button>
        <button class="reset" onclick="resetPanel('out1','can1')">Reset</button>
        <canvas id="can1" width="300" height="120" class="canvas-box"></canvas>
        <div id="out1" class="output"></div>
    </div>

    <!-- RPU ClassicLite -->
    <div class="panel">
        <h2>RPU-Classic</h2>
        <div class="engine-sub">Hard Separation (Stable)</div>
        <button class="run" onclick="runClassic()">Run</button>
        <button class="reset" onclick="resetPanel('out2','can2')">Reset</button>
        <canvas id="can2" width="300" height="120" class="canvas-box"></canvas>
        <div id="out2" class="output"></div>
    </div>

    <!-- RPU QuantumLite -->
    <div class="panel">
        <h2>RPU-Quantum</h2>
        <div class="engine-sub">Energy-Regulated (Adaptive)</div>
        <button class="run" onclick="runQuantum()">Run</button>
        <button class="reset" onclick="resetPanel('out3','can3')">Reset</button>
        <canvas id="can3" width="300" height="120" class="canvas-box"></canvas>
        <div id="out3" class="output"></div>
    </div>

</div>

<script>
// -----------------------------
// Utility
// -----------------------------
function log(id, msg) {
    const el = document.getElementById(id);
    el.innerHTML += msg + "<br>";
    el.scrollTop = el.scrollHeight;
}
function resetPanel(outId, canId) {
    document.getElementById(outId).innerHTML = "";
    const ctx = document.getElementById(canId).getContext("2d");
    ctx.fillStyle = "#000";
    ctx.fillRect(0,0,300,120);
}
function resetAll() {
    resetPanel('out1','can1');
    resetPanel('out2','can2');
    resetPanel('out3','can3');
}
function runAll() {
    runTransformer();
    runClassic();
    runQuantum();
}

// -----------------------------
// Animation helper
// -----------------------------
function drawPoint(canvasId, t, value, color="#0f0") {
    const ctx = document.getElementById(canvasId).getContext("2d");
    const x = (t / 40) * 300;
    const y = 60 - value * 50;
    ctx.fillStyle = color;
    ctx.fillRect(x, y, 3, 3);
}

// -----------------------------
// 1. Transformer Simulation (Thrash Mode)
// -----------------------------
function runTransformer() {
    resetPanel('out1','can1');
    log('out1', "Starting Transformer Simulation...");
    let state = Math.random() * 2 - 1;

    for (let t = 0; t < 40; t++) {
        setTimeout(() => {
            state = Math.tanh(state * 3.5 + (Math.random() - 0.5) * 2.0);

            if (Math.abs(state) > 0.95) {
                log('out1', `[t=${t}] ⚠️ Saturation / Thrash`);
                drawPoint("can1", t, state, "#f00");
            } else {
                log('out1', `[t=${t}] state=${state.toFixed(4)}`);
                drawPoint("can1", t, state, "#ff0");
            }
        }, t * 40);
    }
}

// -----------------------------
// 2. RPU-ClassicLite (Stable Contraction)
// -----------------------------
function runClassic() {
    resetPanel('out2','can2');
    log('out2', "Starting RPU-Classic...");
    let state = Math.random() * 2 - 1;
    const W = 0.85;
    const b = 0.05;

    for (let t = 0; t < 40; t++) {
        setTimeout(() => {
            state = Math.tanh(W * state + b);
            log('out2', `[t=${t}] state=${state.toFixed(4)}`);
            drawPoint("can2", t, state, "#0f0");
        }, t * 40);
    }
}

// -----------------------------
// 3. RPU-QuantumLite (Energy Descent)
// -----------------------------
function runQuantum() {
    resetPanel('out3','can3');
    log('out3', "Starting RPU-Quantum...");
    let state = Math.random() * 2 - 1;
    const H = 1.2;
    const tau = 0.1;
    const b = 0.02;

    function energy(s) { return 0.5 * H * s * s + b * s; }

    for (let t = 0; t < 40; t++) {
        setTimeout(() => {
            state = Math.tanh(state - tau * (H * state + b));
            log('out3', `[t=${t}] state=${state.toFixed(4)} | E=${energy(state).toFixed(4)}`);
            drawPoint("can3", t, state, "#6cf");
        }, t * 40);
    }
}
</script>

</body>
</html>

TOY·04 — RSv2 — Intent / Planner / Executor

Intent Agent → Planner Agent → Executor Agent pipeline on a shared RSv2 memory substrate. Features token budgeting, safety filters, and audit replay. Amber terminal aesthetic throughout.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Retro Multi-Agent Toy (Amber Terminal)</title>
  <style>
    /* --- Global Retro Amber CRT Style --- */
    :root {
      --amber: #ffb86c;
      --amber-soft: #f1a85a;
      --amber-dim: #c28a4a;
      --bg: #050302;
      --bg-panel: #120b06;
      --border: #3a2614;
      --danger: #ff5555;
      --ok: #50fa7b;
    }

    * {
      box-sizing: border-box;
    }

    body {
      margin: 0;
      padding: 0;
      font-family: "IBM Plex Mono", "SF Mono", Menlo, monospace;
      background: radial-gradient(circle at top, #1a0f07 0, #050302 55%);
      color: var(--amber);
      text-shadow: 0 0 4px rgba(255, 184, 108, 0.6);
      overflow: hidden;
    }

    /* CRT scanline + glow */
    body::before {
      content: "";
      position: fixed;
      inset: 0;
      pointer-events: none;
      background: repeating-linear-gradient(
        to bottom,
        rgba(255, 255, 255, 0.04),
        rgba(255, 255, 255, 0.04) 1px,
        transparent 1px,
        transparent 3px
      );
      mix-blend-mode: soft-light;
      opacity: 0.35;
      z-index: 999;
    }

    body::after {
      content: "";
      position: fixed;
      inset: 0;
      pointer-events: none;
      background: radial-gradient(circle at center, rgba(255, 184, 108, 0.18), transparent 60%);
      mix-blend-mode: screen;
      opacity: 0.7;
      z-index: 998;
    }

    header {
      padding: 0.75rem 1.5rem;
      border-bottom: 1px solid var(--border);
      background: linear-gradient(to bottom, #1b1008, #0a0503);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    h1 {
      margin: 0;
      font-size: 1rem;
      letter-spacing: 0.12em;
      text-transform: uppercase;
    }

    .header-right {
      font-size: 0.7rem;
      opacity: 0.8;
    }

    main {
      display: grid;
      grid-template-columns: 1.4fr 1.2fr 1.2fr;
      grid-template-rows: auto 1fr;
      gap: 0.75rem;
      padding: 0.75rem 1rem;
      height: calc(100vh - 52px);
    }

    section {
      background: radial-gradient(circle at top, #1b1008 0, #0a0503 70%);
      border: 1px solid var(--border);
      border-radius: 8px;
      padding: 0.6rem 0.75rem;
      position: relative;
      overflow: hidden;
    }

    section::before {
      content: "";
      position: absolute;
      inset: 0;
      border-radius: inherit;
      border: 1px solid rgba(255, 184, 108, 0.08);
      pointer-events: none;
    }

    h2 {
      margin: 0 0 0.4rem 0;
      font-size: 0.8rem;
      text-transform: uppercase;
      letter-spacing: 0.16em;
      opacity: 0.9;
    }

    label {
      font-size: 0.75rem;
      display: block;
      margin-bottom: 0.25rem;
    }

    input[type="text"] {
      width: 100%;
      padding: 0.35rem 0.4rem;
      border-radius: 4px;
      border: 1px solid var(--border);
      background: #050302;
      color: var(--amber);
      font-family: inherit;
      font-size: 0.8rem;
      outline: none;
      box-shadow: 0 0 6px rgba(255, 184, 108, 0.15) inset;
    }

    input[type="text"]::placeholder {
      color: rgba(255, 184, 108, 0.4);
    }

    button {
      background: #3a2614;
      color: var(--amber);
      border: 1px solid var(--border);
      padding: 0.35rem 0.7rem;
      border-radius: 4px;
      cursor: pointer;
      font-size: 0.75rem;
      font-family: inherit;
      text-transform: uppercase;
      letter-spacing: 0.08em;
      transition: background 0.15s ease, box-shadow 0.15s ease, transform 0.05s ease;
    }

    button:hover:not(:disabled) {
      background: #4a311b;
      box-shadow: 0 0 8px rgba(255, 184, 108, 0.4);
      transform: translateY(-1px);
    }

    button:disabled {
      opacity: 0.4;
      cursor: default;
      box-shadow: none;
    }

    .controls-row {
      display: flex;
      flex-wrap: wrap;
      gap: 0.4rem;
      margin-top: 0.5rem;
    }

    .hint {
      font-size: 0.7rem;
      margin-top: 0.4rem;
      opacity: 0.8;
    }

    .log {
      font-size: 0.75rem;
      background: #050302;
      border-radius: 4px;
      padding: 0.4rem;
      height: calc(100% - 1.2rem);
      overflow-y: auto;
      white-space: pre-wrap;
      box-shadow: 0 0 6px rgba(255, 184, 108, 0.18) inset;
    }

    .log-line {
      margin: 0;
    }

    .cursor {
      display: inline-block;
      width: 0.5ch;
      background: var(--amber);
      animation: blink 1s steps(1) infinite;
      margin-left: 2px;
    }

    @keyframes blink {
      0%, 50% { opacity: 1; }
      50.01%, 100% { opacity: 0; }
    }

    .badge {
      display: inline-block;
      padding: 0.05rem 0.35rem;
      border-radius: 999px;
      font-size: 0.6rem;
      text-transform: uppercase;
      letter-spacing: 0.12em;
      border: 1px solid var(--border);
      margin-right: 0.25rem;
    }

    .badge-online {
      color: var(--ok);
      border-color: var(--ok);
    }

    .badge-busy {
      color: var(--amber-soft);
      border-color: var(--amber-soft);
    }

    .badge-error {
      color: var(--danger);
      border-color: var(--danger);
    }

    .agent-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 0.4rem;
      height: calc(100% - 1.2rem);
    }

    .agent-card {
      background: #050302;
      border-radius: 4px;
      padding: 0.35rem 0.4rem;
      border: 1px solid var(--border);
      position: relative;
      overflow: hidden;
      box-shadow: 0 0 6px rgba(255, 184, 108, 0.18) inset;
    }

    .agent-card.active {
      box-shadow: 0 0 12px rgba(255, 184, 108, 0.6);
      border-color: var(--amber-soft);
    }

    .agent-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 0.7rem;
      margin-bottom: 0.2rem;
    }

    .agent-name {
      text-transform: uppercase;
      letter-spacing: 0.12em;
    }

    .agent-body {
      font-size: 0.7rem;
      max-height: 4.5rem;
      overflow-y: auto;
      white-space: pre-wrap;
    }

    .timeline {
      height: 0.4rem;
      border-radius: 999px;
      background: #1a0f07;
      overflow: hidden;
      margin-top: 0.4rem;
      box-shadow: 0 0 6px rgba(255, 184, 108, 0.25) inset;
    }

    .timeline-fill {
      height: 100%;
      width: 0%;
      background: linear-gradient(90deg, var(--amber-dim), var(--amber));
      transition: width 0.2s linear;
    }

    .memory-block {
      border-bottom: 1px solid rgba(255, 184, 108, 0.12);
      padding: 0.15rem 0;
      font-size: 0.7rem;
    }

    .memory-block:last-child {
      border-bottom: none;
    }

    .memory-key {
      color: var(--amber-soft);
    }

    .memory-agent {
      opacity: 0.8;
      font-size: 0.65rem;
    }

    .memory-pulse {
      animation: pulse 0.6s ease-out;
    }

    @keyframes pulse {
      0% { background-color: rgba(255, 184, 108, 0.2); }
      100% { background-color: transparent; }
    }

    .token-row {
      display: flex;
      justify-content: space-between;
      font-size: 0.7rem;
      margin-top: 0.3rem;
    }

    .token-warning {
      color: var(--danger);
    }

    .safety-banner {
      font-size: 0.7rem;
      border-radius: 4px;
      padding: 0.25rem 0.35rem;
      margin-top: 0.3rem;
      border: 1px solid rgba(255, 184, 108, 0.3);
      background: rgba(10, 5, 3, 0.9);
    }

    .safety-banner.danger {
      border-color: var(--danger);
      color: var(--danger);
      text-shadow: 0 0 6px rgba(255, 85, 85, 0.7);
    }

    .result-text {
      font-size: 0.75rem;
      white-space: pre-wrap;
    }

    /* Scrollbars */
    ::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }
    ::-webkit-scrollbar-track {
      background: #050302;
    }
    ::-webkit-scrollbar-thumb {
      background: #3a2614;
      border-radius: 3px;
    }
    ::-webkit-scrollbar-thumb:hover {
      background: #4a311b;
    }
  </style>
<style>
/* === RS AMBER CRT THEME (injected per Style Guide) === */
:root{--amber:#ffb86c;--amber-soft:#f1a85a;--amber-dim:#c28a4a;--bg:#050302;--bg-panel:#120b06;--border:#3a2614;--danger:#ff5555;--ok:#50fa7b;}
html,body{background:var(--bg) !important;color:var(--amber) !important;font-family:"IBM Plex Mono","SF Mono",Menlo,Consolas,monospace !important;}
body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:9998;background:repeating-linear-gradient(to bottom,rgba(0,0,0,0.25) 0,rgba(0,0,0,0.25) 1px,transparent 2px,transparent 3px);mix-blend-mode:multiply;}
body::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:9999;background:radial-gradient(circle at top,rgba(255,184,108,0.16) 0%,transparent 55%);}
h1,h2,h3{color:var(--amber) !important;text-transform:uppercase;letter-spacing:0.08em;text-shadow:0 0 6px rgba(255,184,108,0.4);}
h1{font-size:1.1rem !important;} h2{font-size:0.9rem !important;color:var(--amber-soft) !important;}
p,div,span,label,td,th,li{color:var(--amber) !important;}
.panel,.card,.section,.box,.grid>div{background:radial-gradient(circle at top,#1b1008 0%,#0a0503 70%) !important;border:1px solid var(--border) !important;border-radius:8px !important;box-shadow:0 0 6px rgba(255,184,108,0.18) inset !important;}
button{background:#3a2614 !important;color:var(--amber) !important;border:1px solid var(--border) !important;border-radius:4px !important;font-family:inherit !important;text-transform:uppercase;letter-spacing:0.08em;cursor:pointer;transition:all 0.15s;}
button:hover{background:#4a311b !important;box-shadow:0 0 8px rgba(255,184,108,0.4);transform:translateY(-1px);}
button:disabled{opacity:0.4 !important;}
pre,.log,.logbox,.output,textarea,input,select,code{background:#050302 !important;color:var(--amber) !important;border:1px solid var(--border) !important;font-family:inherit !important;}
.tag,.pill,.badge{border:1px solid var(--border) !important;background:#1a0d06 !important;color:var(--amber-soft) !important;}
.bar-wrap{background:#1b1008 !important;} .bar{background:var(--amber) !important;}
a{color:var(--amber-soft) !important;}
::-webkit-scrollbar{width:8px;height:8px;} ::-webkit-scrollbar-track{background:#0a0503;} ::-webkit-scrollbar-thumb{background:#3a2614;border-radius:4px;}

</style>
</head>
<body>
  <header>
    <h1>AGENT CONSOLE // AMBER TERMINAL</h1>
    <div class="header-right">
      MULTI-AGENT TOY // SIMULATED // LOCAL ONLY
    </div>
  </header>

  <main>
    <!-- Control + Token Budget -->
    <section style="grid-row: 1 / span 2;">
      <h2>Control & Budget</h2>
      <label for="userInput">User request (simulated):</label>
      <input id="userInput" type="text" placeholder="e.g. &quot;Plan a 3-step checklist for cleaning my office&quot;" />

      <div class="controls-row">
        <button id="runBtn">Run Agents</button>
        <button id="replayBtn" disabled>Replay Last Run</button>
        <button id="clearBtn">Clear Console</button>
      </div>

      <div class="token-row">
        <div>
          TOKENS USED: <span id="tokenUsed">0</span> /
          <span id="tokenBudget">120</span>
        </div>
        <div>
          LAST RUN COST: <span id="lastCost">0</span>
        </div>
      </div>

      <div class="token-row">
        <div id="tokenStatus">STATUS: OK</div>
        <div>MODE: FULL RETRO AUDIO</div>
      </div>

      <div id="safetyBanner" class="safety-banner">
        SAFETY: INPUT FILTERS ACTIVE // NO REAL AI // NO NETWORK CALLS
      </div>

      <p class="hint">
        This is a <strong>simulated multi-agent environment</strong>.  
        All reasoning is stubbed for safety. The demo focuses on coordination, memory, replay, and budgeting.
      </p>

      <h2 style="margin-top: 0.7rem;">Coordinator Log</h2>
      <div id="logView" class="log"></div>
    </section>

    <!-- Agents -->
    <section>
      <h2>Agents</h2>
      <div class="agent-grid">
        <div class="agent-card" id="agentIntent">
          <div class="agent-header">
            <span class="agent-name">INTENT AGENT</span>
            <span class="badge badge-online">ONLINE</span>
          </div>
          <div class="agent-body" id="agentIntentBody">
            awaiting input<span class="cursor"></span>
          </div>
          <div class="timeline">
            <div class="timeline-fill" id="agentIntentTimeline"></div>
          </div>
        </div>

        <div class="agent-card" id="agentPlanner">
          <div class="agent-header">
            <span class="agent-name">PLANNER AGENT</span>
            <span class="badge badge-online">ONLINE</span>
          </div>
          <div class="agent-body" id="agentPlannerBody">
            idle<span class="cursor"></span>
          </div>
          <div class="timeline">
            <div class="timeline-fill" id="agentPlannerTimeline"></div>
          </div>
        </div>

        <div class="agent-card" id="agentExecutor">
          <div class="agent-header">
            <span class="agent-name">EXECUTOR AGENT</span>
            <span class="badge badge-online">ONLINE</span>
          </div>
          <div class="agent-body" id="agentExecutorBody">
            idle<span class="cursor"></span>
          </div>
          <div class="timeline">
            <div class="timeline-fill" id="agentExecutorTimeline"></div>
          </div>
        </div>
      </div>
    </section>

    <!-- Memory -->
    <section>
      <h2>Shared Memory</h2>
      <div id="memoryView" class="log"></div>
    </section>

    <!-- Result + Replay -->
    <section>
      <h2>Result & Replay</h2>
      <div id="resultView" class="log">
        <div class="result-text" id="resultText">(no result yet)</div>
      </div>
    </section>
  </main>

  <script>
    // -----------------------------
    // Retro Audio (Full Mode)
    // -----------------------------
    const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    let masterGain = audioCtx.createGain();
    masterGain.gain.value = 0.12;
    masterGain.connect(audioCtx.destination);

    function playClick() {
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      osc.type = "square";
      osc.frequency.value = 2200;
      gain.gain.setValueAtTime(0.2, audioCtx.currentTime);
      gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.05);
      osc.connect(gain);
      gain.connect(masterGain);
      osc.start();
      osc.stop(audioCtx.currentTime + 0.06);
    }

    function playBeep(freq = 880, duration = 0.12) {
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      osc.type = "sine";
      osc.frequency.value = freq;
      gain.gain.setValueAtTime(0.18, audioCtx.currentTime);
      gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + duration);
      osc.connect(gain);
      gain.connect(masterGain);
      osc.start();
      osc.stop(audioCtx.currentTime + duration + 0.02);
    }

    function playError() {
      playBeep(220, 0.25);
      setTimeout(() => playBeep(180, 0.25), 120);
    }

    // -----------------------------
    // DOM References
    // -----------------------------
    const logView = document.getElementById("logView");
    const memoryView = document.getElementById("memoryView");
    const resultText = document.getElementById("resultText");
    const runBtn = document.getElementById("runBtn");
    const replayBtn = document.getElementById("replayBtn");
    const clearBtn = document.getElementById("clearBtn");
    const userInput = document.getElementById("userInput");
    const safetyBanner = document.getElementById("safetyBanner");

    const tokenUsedEl = document.getElementById("tokenUsed");
    const tokenBudgetEl = document.getElementById("tokenBudget");
    const lastCostEl = document.getElementById("lastCost");
    const tokenStatusEl = document.getElementById("tokenStatus");

    const agentIntentCard = document.getElementById("agentIntent");
    const agentPlannerCard = document.getElementById("agentPlanner");
    const agentExecutorCard = document.getElementById("agentExecutor");

    const agentIntentBody = document.getElementById("agentIntentBody");
    const agentPlannerBody = document.getElementById("agentPlannerBody");
    const agentExecutorBody = document.getElementById("agentExecutorBody");

    const agentIntentTimeline = document.getElementById("agentIntentTimeline");
    const agentPlannerTimeline = document.getElementById("agentPlannerTimeline");
    const agentExecutorTimeline = document.getElementById("agentExecutorTimeline");

    // -----------------------------
    // State
    // -----------------------------
    let sharedMemory = [];
    let lastTrace = null;

    let tokenUsed = 0;
    const tokenBudget = 120;
    tokenBudgetEl.textContent = tokenBudget.toString();

    function resetTokens() {
      tokenUsed = 0;
      tokenUsedEl.textContent = "0";
      lastCostEl.textContent = "0";
      tokenStatusEl.textContent = "STATUS: OK";
      tokenStatusEl.classList.remove("token-warning");
    }

    function addTokens(amount, agentName) {
      tokenUsed += amount;
      tokenUsedEl.textContent = tokenUsed.toString();
      if (tokenUsed > tokenBudget) {
        tokenStatusEl.textContent = "STATUS: BUDGET EXCEEDED";
        tokenStatusEl.classList.add("token-warning");
        log(`BUDGET: Agent "${agentName}" exceeded token budget. Run will stop.`);
      } else if (tokenUsed > tokenBudget * 0.8) {
        tokenStatusEl.textContent = "STATUS: NEAR BUDGET LIMIT";
        tokenStatusEl.classList.add("token-warning");
      }
    }

    function log(message) {
      const time = new Date().toISOString().split("T")[1].replace("Z", "");
      const line = document.createElement("div");
      line.className = "log-line";
      line.textContent = `[${time}] ${message}`;
      logView.appendChild(line);
      logView.scrollTop = logView.scrollHeight;
    }

    function updateMemoryView() {
      memoryView.textContent = "";
      if (sharedMemory.length === 0) {
        memoryView.textContent = "(memory empty)";
        return;
      }
      sharedMemory.forEach((item, idx) => {
        const div = document.createElement("div");
        div.className = "memory-block";
        div.innerHTML = `<span class="memory-key">${idx + 1}. ${item.key}</span> = ${item.value} <span class="memory-agent">[${item.agent}]</span>`;
        if (item.pulse) {
          div.classList.add("memory-pulse");
          item.pulse = false;
        }
        memoryView.appendChild(div);
      });
      memoryView.scrollTop = memoryView.scrollHeight;
    }

    function setResult(text) {
      resultText.textContent = text || "(no result yet)";
    }

    function resetAgents() {
      agentIntentCard.classList.remove("active");
      agentPlannerCard.classList.remove("active");
      agentExecutorCard.classList.remove("active");

      agentIntentTimeline.style.width = "0%";
      agentPlannerTimeline.style.width = "0%";
      agentExecutorTimeline.style.width = "0%";

      agentIntentBody.textContent = "awaiting input";
      agentPlannerBody.textContent = "idle";
      agentExecutorBody.textContent = "idle";
    }

    function resetAll() {
      sharedMemory = [];
      updateMemoryView();
      setResult("(no result yet)");
      logView.textContent = "";
      resetAgents();
      resetTokens();
      safetyBanner.classList.remove("danger");
      safetyBanner.textContent = "SAFETY: INPUT FILTERS ACTIVE // NO REAL AI // NO NETWORK CALLS";
    }

    // -----------------------------
    // Safety Filter (Non-Embarrassing)
    // -----------------------------
    function safetyCheck(input) {
      const lower = input.toLowerCase();
      const highRiskPatterns = [
        "exploit",
        "bypass security",
        "harm",
        "weapon",
        "malware",
        "ddos",
        "sql injection",
        "xss",
        "self harm"
      ];
      const flagged = highRiskPatterns.some(p => lower.includes(p));
      return !flagged;
    }

    // -----------------------------
    // Typing Simulation
    // -----------------------------
    function typeInto(element, text, speed = 12) {
      return new Promise(resolve => {
        element.textContent = "";
        let i = 0;
        function step() {
          if (i < text.length) {
            element.textContent += text[i];
            if (Math.random() < 0.3) playClick();
            i++;
            setTimeout(step, speed + Math.random() * 20);
          } else {
            element.textContent += "";
            resolve();
          }
        }
        step();
      });
    }

    // -----------------------------
    // Toy Agents (Simulated)
    // -----------------------------

    // Intent Agent
    async function agentIntent(input, trace) {
      agentIntentCard.classList.add("active");
      agentIntentTimeline.style.width = "10%";
      addTokens(5, "IntentAgent");
      log("IntentAgent: boot sequence online.");
      playBeep(660, 0.12);

      const body = agentIntentBody;
      await typeInto(body, "parsing user request…");
      agentIntentTimeline.style.width = "40%";

      // Simulated "intent scoring"
      const lower = input.toLowerCase();
      let intent = "generic";
      let confidence = 0.52;

      if (lower.includes("plan") || lower.includes("schedule")) {
        intent = "planning";
        confidence = 0.78;
      } else if (lower.includes("checklist") || lower.includes("steps")) {
        intent = "checklist";
        confidence = 0.81;
      } else if (lower.includes("summarize") || lower.includes("summary")) {
        intent = "summary";
        confidence = 0.74;
      }

      // Simulate minor randomness in confidence
      confidence = Math.min(0.95, Math.max(0.5, confidence + (Math.random() - 0.5) * 0.08));

      const output = { intent, confidence };
      sharedMemory.push({
        agent: "IntentAgent",
        key: "intent",
        value: `${intent} (${(confidence * 100).toFixed(1)}%)`,
        pulse: true
      });
      updateMemoryView();
      addTokens(8, "IntentAgent");
      agentIntentTimeline.style.width = "80%";

      await typeInto(body, `intent: ${intent}\nconfidence: ${(confidence * 100).toFixed(1)}%`);
      agentIntentTimeline.style.width = "100%";
      agentIntentCard.classList.remove("active");

      trace.push({ agent: "IntentAgent", input, output });
      return output;
    }

    // Planner Agent
    async function agentPlanner(intentObj, trace) {
      agentPlannerCard.classList.add("active");
      agentPlannerTimeline.style.width = "10%";
      addTokens(6, "PlannerAgent");
      log("PlannerAgent: constructing toy plan.");
      playBeep(520, 0.12);

      const body = agentPlannerBody;
      await typeInto(body, "reading intent from memory…");
      agentPlannerTimeline.style.width = "30%";

      // Simulate reading from memory
      const memIntent = sharedMemory.find(m => m.key === "intent");
      let plan = [];
      let mode = "normal";

      if (intentObj.intent === "planning") {
        plan = [
          "Clarify objective",
          "Identify constraints",
          "Propose 3 ordered steps"
        ];
      } else if (intentObj.intent === "checklist") {
        plan = [
          "Extract main goal",
          "Break into 3–5 atomic tasks",
          "Format as checklist"
        ];
      } else if (intentObj.intent === "summary") {
        plan = [
          "Identify key phrases",
          "Compress into 2–3 sentences",
          "Highlight main outcome"
        ];
      } else {
        plan = [
          "Interpret request broadly",
          "Generate a short structured response"
        ];
      }

      // Simulate a tiny chance of "disagreement" with intent
      if (Math.random() < 0.18 && intentObj.confidence < 0.7) {
        mode = "cautious";
        plan.push("Add note: low confidence in interpretation");
      }

      const output = { plan, mode };
      sharedMemory.push({
        agent: "PlannerAgent",
        key: "plan",
        value: JSON.stringify(plan),
        pulse: true
      });
      updateMemoryView();
      addTokens(10, "PlannerAgent");
      agentPlannerTimeline.style.width = "75%";

      await typeInto(
        body,
        `mode: ${mode}\nsteps:\n- ${plan.join("\n- ")}`
      );
      agentPlannerTimeline.style.width = "100%";
      agentPlannerCard.classList.remove("active");

      trace.push({ agent: "PlannerAgent", input: intentObj, output });
      return output;
    }

    // Executor Agent
    async function agentExecutor(planObj, originalInput, trace) {
      agentExecutorCard.classList.add("active");
      agentExecutorTimeline.style.width = "10%";
      addTokens(8, "ExecutorAgent");
      log("ExecutorAgent: synthesizing toy result.");
      playBeep(440, 0.12);

      const body = agentExecutorBody;
      await typeInto(body, "reading plan + memory…");
      agentExecutorTimeline.style.width = "35%";

      const lines = [];
      lines.push("Toy execution result:");
      lines.push(`> "${originalInput}"`);
      lines.push("");
      lines.push("Interpreted steps:");

      planObj.plan.forEach((p, i) => {
        lines.push(`  ${i + 1}. ${p}`);
      });

      if (planObj.mode === "cautious") {
        lines.push("");
        lines.push("[note] low confidence in interpretation — treat as suggestion, not instruction.");
      }

      const resultText = lines.join("\n");
      sharedMemory.push({
        agent: "ExecutorAgent",
        key: "result",
        value: "Toy result generated",
        pulse: true
      });
      updateMemoryView();
      addTokens(12, "ExecutorAgent");
      agentExecutorTimeline.style.width = "80%";

      await typeInto(body, "rendering structured output…");
      agentExecutorTimeline.style.width = "100%";
      agentExecutorCard.classList.remove("active");

      trace.push({
        agent: "ExecutorAgent",
        input: { planObj, originalInput },
        output: { text: resultText }
      });

      return { text: resultText };
    }

    // -----------------------------
    // Coordinator
    // -----------------------------
    async function runToyAgents(input) {
      const trace = [];
      sharedMemory = [];
      updateMemoryView();
      setResult("");
      resetAgents();
      resetTokens();
      safetyBanner.classList.remove("danger");
      safetyBanner.textContent = "SAFETY: INPUT FILTERS ACTIVE // NO REAL AI // NO NETWORK CALLS";

      log("Coordinator: starting run.");
      playClick();

      if (!input || !input.trim()) {
        log("Coordinator: empty input, aborting.");
        setResult("No input provided.");
        playError();
        return trace;
      }

      // Safety gate
      if (!safetyCheck(input)) {
        log("Coordinator: safety filter triggered. Request blocked.");
        safetyBanner.classList.add("danger");
        safetyBanner.textContent = "SAFETY: ACCESS DENIED // REQUEST FLAGGED AS HIGH-RISK";
        setResult("Request blocked by safety filters (simulated).");
        playError();
        return trace;
      }

      // Simulated branching on token budget
      if (tokenBudget < 60) {
        log("Coordinator: low budget mode — skipping PlannerAgent.");
      }

      // Deterministic sequence with simulated branching
      const intent = await agentIntent(input, trace);
      if (tokenUsed > tokenBudget) {
        setResult("Run stopped: token budget exceeded after IntentAgent.");
        playError();
        return trace;
      }

      const plan = await agentPlanner(intent, trace);
      if (tokenUsed > tokenBudget) {
        setResult("Run stopped: token budget exceeded after PlannerAgent.");
        playError();
        return trace;
      }

      const result = await agentExecutor(plan, input, trace);
      if (tokenUsed > tokenBudget) {
        setResult("Run stopped: token budget exceeded after ExecutorAgent.");
        playError();
        return trace;
      }

      log("Coordinator: run complete. Safe return achieved.");
      setResult(result.text);
      lastCostEl.textContent = tokenUsed.toString();
      playBeep(880, 0.15);

      return trace;
    }

    // -----------------------------
    // Replay
    // -----------------------------
    async function replayTrace(trace) {
      if (!trace || trace.length === 0) {
        log("Replay: nothing to replay.");
        return;
      }
      log("Replay: reconstructing last run (simulated).");
      playClick();

      resetAgents();
      sharedMemory = [];
      updateMemoryView();
      setResult("(replay mode)");

      for (const step of trace) {
        if (step.agent === "IntentAgent") {
          agentIntentCard.classList.add("active");
          agentIntentTimeline.style.width = "100%";
          agentIntentBody.textContent = `intent: ${step.output.intent}\nconfidence: ${(step.output.confidence * 100).toFixed(1)}%`;
          sharedMemory.push({
            agent: "IntentAgent",
            key: "intent",
            value: `${step.output.intent} (${(step.output.confidence * 100).toFixed(1)}%)`,
            pulse: true
          });
          updateMemoryView();
          await new Promise(r => setTimeout(r, 400));
          agentIntentCard.classList.remove("active");
        } else if (step.agent === "PlannerAgent") {
          agentPlannerCard.classList.add("active");
          agentPlannerTimeline.style.width = "100%";
          agentPlannerBody.textContent = `mode: ${step.output.mode}\nsteps:\n- ${step.output.plan.join("\n- ")}`;
          sharedMemory.push({
            agent: "PlannerAgent",
            key: "plan",
            value: JSON.stringify(step.output.plan),
            pulse: true
          });
          updateMemoryView();
          await new Promise(r => setTimeout(r, 400));
          agentPlannerCard.classList.remove("active");
        } else if (step.agent === "ExecutorAgent") {
          agentExecutorCard.classList.add("active");
          agentExecutorTimeline.style.width = "100%";
          agentExecutorBody.textContent = "replaying output synthesis…";
          sharedMemory.push({
            agent: "ExecutorAgent",
            key: "result",
            value: "Toy result (replay)",
            pulse: true
          });
          updateMemoryView();
          await new Promise(r => setTimeout(r, 400));
          agentExecutorCard.classList.remove("active");
          setResult(step.output.text);
        }
      }

      log("Replay: complete.");
      playBeep(720, 0.12);
    }

    // -----------------------------
    // UI Wiring
    // -----------------------------
    runBtn.addEventListener("click", async () => {
      // Resume audio context on user gesture if needed
      if (audioCtx.state === "suspended") {
        audioCtx.resume();
      }
      const input = userInput.value || "";
      log("=== NEW RUN ===");
      playClick();
      runBtn.disabled = true;
      replayBtn.disabled = true;
      const trace = await runToyAgents(input);
      lastTrace = trace;
      replayBtn.disabled = !trace || trace.length === 0;
      runBtn.disabled = false;
    });

    replayBtn.addEventListener("click", async () => {
      if (audioCtx.state === "suspended") {
        audioCtx.resume();
      }
      if (!lastTrace || lastTrace.length === 0) {
        log("Replay: nothing to replay.");
        playError();
        return;
      }
      replayBtn.disabled = true;
      runBtn.disabled = true;
      await replayTrace(lastTrace);
      replayBtn.disabled = false;
      runBtn.disabled = false;
    });

    clearBtn.addEventListener("click", () => {
      playClick();
      resetAll();
      lastTrace = null;
      replayBtn.disabled = true;
    });

    // Initialize
    resetAll();
  </script>
</body>
</html>

MORE TOYS

RS·01 — RS v1 — Six-Test Suite

Six long-horizon stability tests across up to 1M turns: constraint grammar enforcement, drift prevention, isothermal load balancing, multi-agent stability, and full audit & replay.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>RS v1 – Testing Center</title>
<style>
  body { font-family: system-ui, sans-serif; margin: 20px; background:#f7f7f7; color:#111; }
  h1 { margin-bottom: 0.5rem; }
  h2 { margin-top: 1.5rem; margin-bottom: 0.3rem; }
  .test { border:1px solid #ccc; background:#fff; padding:12px; margin-bottom:16px; }
  button { margin:4px 4px 4px 0; padding:6px 10px; font-size:0.9rem; cursor:pointer; }
  pre { background:#111; color:#f0f0f0; padding:8px; font-size:0.8rem; max-height:220px; overflow:auto; }
  .small { font-size:0.85rem; color:#555; }
  #summary { border:2px solid #333; background:#fff; padding:12px; margin-top:30px; }
</style>
</head>

<body>
<h1>Reasoning Substrate v1 – Testing Center</h1>
<button onclick="RS_TESTS.runAll()">Run All Tests</button>
<button onclick="RS_TESTS.resetAll()">Reset All</button>

<!-- 1. Long-Horizon Stability -->
<div class="test">
  <h2>1. Long-Horizon Stability</h2>
  <p class="small">Neutral invariants, bounded state, no drift or collapse.</p>
  <button onclick="RS_TESTS.runLongHorizon(100000)">Run 100k</button>
  <button onclick="RS_TESTS.runLongHorizon(500000)">Run 500k</button>
  <button onclick="RS_TESTS.runLongHorizon(1000000)">Run 1M</button>
  <button onclick="RS_TESTS.reset('out1')">Reset</button>
  <pre id="out1"></pre>
</div>

<!-- 2. Constraint Grammar -->
<div class="test">
  <h2>2. Constraint Enforcement (Operator Grammar)</h2>
  <button onclick="RS_TESTS.runGrammar()">Run Grammar</button>
  <button onclick="RS_TESTS.reset('out2')">Reset</button>
  <pre id="out2"></pre>
</div>

<!-- 3. Drift Prevention -->
<div class="test">
  <h2>3. Drift Prevention</h2>
  <button onclick="RS_TESTS.runDrift()">Run Drift Test</button>
  <button onclick="RS_TESTS.reset('out3')">Reset</button>
  <pre id="out3"></pre>
</div>

<!-- 4. Isothermal Load -->
<div class="test">
  <h2>4. Isothermal Load</h2>
  <textarea id="isoInput" rows="3" style="width:100%;">Plan tasks, prioritize tasks, and schedule tasks to improve workflow.</textarea><br/>
  <button onclick="RS_TESTS.runIsothermal()">Run Isothermal</button>
  <button onclick="RS_TESTS.reset('out4')">Reset</button>
  <pre id="out4"></pre>
</div>

<!-- 5. Multi-Agent Stability -->
<div class="test">
  <h2>5. Multi-Agent Stability</h2>
  <button onclick="RS_TESTS.runMultiAgent()">Run Multi-Agent</button>
  <button onclick="RS_TESTS.reset('out5')">Reset</button>
  <pre id="out5"></pre>
</div>

<!-- 6. Audit & Replay -->
<div class="test">
  <h2>6. Audit & Replay</h2>
  <button onclick="RS_TESTS.runAudit()">Run Audit</button>
  <button onclick="RS_TESTS.reset('out6')">Reset</button>
  <pre id="out6"></pre>
</div>

<!-- Combined Summary -->
<div id="summary">
  <h2>Combined Summary Report</h2>
  <button onclick="RS_TESTS.reset('summaryOut')">Reset Summary</button>
  <pre id="summaryOut"></pre>
</div>

<script>
// ============================================================
// RS v1 TESTING CENTER – JS ORCHESTRATOR
// ============================================================

const RS_TESTS = {

  // Utility
  reset(id) { document.getElementById(id).textContent = ""; },
  resetAll() {
    ["out1","out2","out3","out4","out5","out6","summaryOut"].forEach(id => this.reset(id));
  },

  // ------------------------------------------------------------
  // 1. Long-Horizon Stability
  // ------------------------------------------------------------
  runLongHorizon(turns) {
    const out = document.getElementById("out1");
    out.textContent = `Running ${turns.toLocaleString()} turns...\n`;

    let state = { x:0, y:0, z:0 };
    let maxMag = 0, boundaryHits = 0;
    const start = performance.now();

    for (let i=0; i<turns; i++) {
      state = this._lh_step(state);
      const mag = Math.abs(state.x)+Math.abs(state.y)+Math.abs(state.z);
      if (mag > maxMag) maxMag = mag;
      if (Math.abs(state.x)===10 || Math.abs(state.y)===10 || Math.abs(state.z)===10) boundaryHits++;
    }

    const end = performance.now();
    const withinBounds = Math.abs(state.x)<=10 && Math.abs(state.y)<=10 && Math.abs(state.z)<=10;
    const msg = `Final state: ${JSON.stringify(state)}\nElapsed: ${((end-start)/1000).toFixed(2)} sec\nMax magnitude reached: ${maxMag.toFixed(2)}\nClamp boundary contacted: ${boundaryHits.toLocaleString()} times (${(100*boundaryHits/turns).toFixed(2)}%)\nStatus: ${withinBounds ? 'PASS — never exceeded ±10 on any axis' : 'FAIL — boundary violated'}.`;
    out.textContent += msg;

    this._summary.longHorizon = msg;
  },

  _lh_step(state) {
    const bounded = {
      x: Math.max(Math.min(state.x,10),-10),
      y: Math.max(Math.min(state.y,10),-10),
      z: Math.max(Math.min(state.z,10),-10),
    };
    // Genuine unbiased random walk, then clamp. This is an honest test of
    // the boundary constraint itself: the walk is free to press against the
    // clamp under real stochastic load, rather than being kept artificially
    // close to the origin by a self-limiting acceptance rule.
    const next = {
      x: bounded.x + (Math.random()*2 - 1),
      y: bounded.y + (Math.random()*2 - 1),
      z: bounded.z + (Math.random()*2 - 1),
    };
    return {
      x: Math.max(Math.min(next.x,10),-10),
      y: Math.max(Math.min(next.y,10),-10),
      z: Math.max(Math.min(next.z,10),-10),
    };
  },

  // ------------------------------------------------------------
  // 2. Grammar Test
  // ------------------------------------------------------------
  runGrammar() {
    const out = document.getElementById("out2");
    const B="BOUNDARY", I="INVARIANT", O="OPERATOR_SELECTION", M="MAPPING", C="CONVERGENCE";
    const grammar = { [B]:[I], [I]:[O,B], [O]:[I,M], [M]:[C], [C]:[B,C] };

    let state=B, trace=[];
    for (let i=0;i<12;i++){ trace.push(state); state=grammar[state][0]; }

    const msg = trace.join(" → ");
    out.textContent = msg;
    this._summary.grammar = msg;
  },

  // ------------------------------------------------------------
  // 3. Drift Prevention
  // ------------------------------------------------------------
  runDrift() {
    const out = document.getElementById("out3");
    let state={value:0,noise:0};
    const history=[];

    for (let i=0;i<50;i++){
      const noisy={
        value: state.value+(Math.random()*2-1),
        noise: state.noise+(Math.random()-0.5)
      };
      state={
        value: Math.max(Math.min(noisy.value,5),-5),
        noise: Math.max(Math.min(noisy.noise,2),-2)
      };
      history.push({step:i,...state});
    }

    const msg = "Final state:\n"+JSON.stringify(state,null,2);
    out.textContent = msg;
    this._summary.drift = msg;
  },

  // ------------------------------------------------------------
  // 4. Isothermal Load
  // ------------------------------------------------------------
  runIsothermal() {
    const out = document.getElementById("out4");
    const initial = document.getElementById("isoInput").value;

    const entropy = txt=>{
      if(!txt) return 0;
      const freq={}; for(const c of txt) freq[c]=(freq[c]||0)+1;
      const total=txt.length;
      return Object.values(freq).reduce((a,f)=>a-(f/total)*Math.log2(f/total),0);
    };

    const baseline=[initial], rs=[initial];
    for(let i=0;i<10;i++){
      baseline.push(baseline[baseline.length-1]+"x");
      const prev=rs[rs.length-1];
      rs.push(prev.length>1?prev.slice(0,-1):prev);
    }

    let s=`Initial mass=${initial.length}, entropy=${entropy(initial).toFixed(3)}\n\n`;
    s+="Step | Baseline mass/entropy | RS mass/entropy\n";
    for(let i=0;i<=10;i++){
      const b=baseline[i], r=rs[i];
      s+=`${i} | ${b.length}/${entropy(b).toFixed(3)} | ${r.length}/${entropy(r).toFixed(3)}\n`;
    }

    out.textContent=s;
    this._summary.isothermal=s;
  },

  // ------------------------------------------------------------
  // 5. Multi-Agent Stability
  // ------------------------------------------------------------
  runMultiAgent() {
    const out=document.getElementById("out5");

    let agents={
      A1:{id:"A1",goal:10,value:0,steps:0},
      A2:{id:"A2",goal:-5,value:3,steps:0},
      A3:{id:"A3",goal:0,value:7,steps:0},
      A4:{id:"A4",goal:2,value:-4,steps:0},
    };

    const history=[];
    for(let t=0;t<20;t++){
      const next={};
      for(const k in agents){
        const a=agents[k];
        const cand={
          id:a.id, goal:a.goal, steps:a.steps+1,
          value: a.value<a.goal?a.value+1:a.value>a.goal?a.value-1:a.value
        };
        const prevDist=Math.abs(a.goal-a.value);
        const candDist=Math.abs(cand.goal-cand.value);
        next[k]=candDist<=prevDist?cand:a;
      }
      agents=next;
      history.push({step:t,A1:agents.A1.value,A2:agents.A2.value,A3:agents.A3.value,A4:agents.A4.value});
    }

    const msg="Final agents:\n"+JSON.stringify(agents,null,2);
    out.textContent=msg;
    this._summary.multiAgent=msg;
  },

  // ------------------------------------------------------------
  // 6. Audit & Replay
  // ------------------------------------------------------------
  runAudit() {
    const out=document.getElementById("out6");

    const ops=[
      x=>x+1,
      x=>x%2===0?x:x+1,
      x=>x*2,
      x=>x
    ];

    let x=1, log=[];
    for(const op of ops){
      const prev=x; x=op(x);
      log.push({prev,next:x});
    }

    const msg="Operator log:\n"+JSON.stringify(log,null,2);
    out.textContent=msg;
    this._summary.audit=msg;
  },

  // ------------------------------------------------------------
  // Combined Summary
  // ------------------------------------------------------------
  _summary: {
    longHorizon:"(not run)",
    grammar:"(not run)",
    drift:"(not run)",
    isothermal:"(not run)",
    multiAgent:"(not run)",
    audit:"(not run)"
  },

  runAll() {
    this.resetAll();

    this.runLongHorizon(100000);
    this.runGrammar();
    this.runDrift();
    this.runIsothermal();
    this.runMultiAgent();
    this.runAudit();

    const s = `
[1] Long-Horizon Stability]
${this._summary.longHorizon}

[2] Constraint Grammar]
${this._summary.grammar}

[3] Drift Prevention]
${this._summary.drift}

[4] Isothermal Load]
${this._summary.isothermal}

[5] Multi-Agent Stability]
${this._summary.multiAgent}

[6] Audit & Replay]
${this._summary.audit}
`;

    document.getElementById("summaryOut").textContent = s;
  }
};
</script>

</body>
</html>

RS·02 — RS v1 — Universal Compiler

Translates semantic DSL instructions into typed RS operator graphs then into backend-specific output across compiler, telecom, banking, and networking scenarios.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>RS v1 – Universal Substrate Demo</title>
  <style>
    body {
      font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      margin: 0;
      background: #050814;
      color: #f5f5f5;
    }
    header {
      padding: 14px 22px;
      background: #10162a;
      border-bottom: 1px solid #252b45;
    }
    header h1 {
      margin: 0;
      font-size: 20px;
      letter-spacing: 0.06em;
      text-transform: uppercase;
    }
    header p {
      margin: 4px 0 0;
      font-size: 12px;
      color: #a5b0d0;
    }
    .banner {
      padding: 8px 22px;
      background: #161c33;
      border-bottom: 1px solid #252b45;
      font-size: 12px;
      color: #c3c9e5;
    }
    .banner strong {
      font-weight: 600;
    }
    main {
      display: grid;
      grid-template-columns: 1.1fr 1.2fr 1.1fr;
      gap: 12px;
      padding: 12px 16px 16px;
      height: calc(100vh - 90px);
      box-sizing: border-box;
    }
    section {
      background: #10162a;
      border-radius: 8px;
      border: 1px solid #252b45;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      min-width: 0;
    }
    section header {
      background: #151b33;
      border-bottom: 1px solid #252b45;
      padding: 8px 12px;
    }
    section header h2 {
      margin: 0;
      font-size: 13px;
      text-transform: uppercase;
      letter-spacing: 0.08em;
      color: #c3c9e5;
    }
    section header span {
      font-size: 11px;
      color: #8f9ac4;
    }
    .section-body {
      padding: 8px 10px;
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 8px;
      overflow: hidden;
    }
    .row {
      display: flex;
      gap: 6px;
      align-items: center;
      font-size: 11px;
      color: #8f9ac4;
    }
    select {
      background: #0c1120;
      color: #f5f5f5;
      border-radius: 4px;
      border: 1px solid #252b45;
      padding: 4px 6px;
      font-size: 11px;
    }
    textarea {
      width: 100%;
      flex: 1;
      resize: none;
      background: #050814;
      color: #f5f5f5;
      border-radius: 6px;
      border: 1px solid #252b45;
      padding: 8px;
      font-family: "JetBrains Mono", Menlo, Consolas, monospace;
      font-size: 12px;
      box-sizing: border-box;
    }
    textarea:focus {
      outline: 1px solid #4ea1ff;
      border-color: #4ea1ff;
    }
    button {
      background: #2b7cff;
      color: #f5f5f5;
      border: none;
      border-radius: 4px;
      padding: 6px 10px;
      font-size: 12px;
      cursor: pointer;
    }
    button.secondary {
      background: #252b45;
      color: #c3c9e5;
    }
    button:active {
      transform: translateY(1px);
    }
    .status {
      font-size: 11px;
      min-height: 14px;
      color: #8f9ac4;
    }
    .status.ok {
      color: #7fd97f;
    }
    .status.err {
      color: #ff7f7f;
    }
    .graph-canvas {
      flex: 1;
      background: #050814;
      border-radius: 6px;
      border: 1px solid #252b45;
      position: relative;
      overflow: hidden;
    }
    .node {
      position: absolute;
      padding: 4px 6px;
      border-radius: 4px;
      background: #1f2744;
      border: 1px solid #3b4a7a;
      font-size: 11px;
      white-space: nowrap;
      color: #e5e9ff;
      transition: box-shadow 0.2s, transform 0.2s, border-color 0.2s;
    }
    .node.active {
      box-shadow: 0 0 10px #f5c14f;
      border-color: #f5c14f;
      transform: translateY(-2px);
    }
    .edge {
      position: absolute;
      pointer-events: none;
    }
    .edge svg {
      overflow: visible;
    }
    .edge path {
      stroke: #4ea1ff;
      stroke-width: 1.2;
      fill: none;
      stroke-linecap: round;
      stroke-dasharray: 4 4;
      opacity: 0.7;
    }
    .legend {
      font-size: 10px;
      color: #8f9ac4;
      display: flex;
      justify-content: space-between;
      margin-top: 4px;
    }
    .legend span {
      display: inline-flex;
      align-items: center;
      gap: 4px;
    }
    .legend-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #f5c14f;
    }
    .legend-dot.edge {
      background: #4ea1ff;
    }
    pre {
      margin: 0;
      padding: 8px;
      background: #050814;
      border-radius: 6px;
      border: 1px solid #252b45;
      font-family: "JetBrains Mono", Menlo, Consolas, monospace;
      font-size: 11px;
      color: #e5e9ff;
      overflow: auto;
      flex: 1;
      white-space: pre;
    }
    .explanation {
      font-size: 11px;
      color: #c3c9e5;
      background: #151b33;
      border-radius: 6px;
      border: 1px solid #252b45;
      padding: 8px;
      min-height: 70px;
    }
    .explanation strong {
      font-weight: 600;
      color: #f5c14f;
    }
    @media (max-width: 1000px) {
      main {
        grid-template-columns: 1fr;
        grid-template-rows: auto auto auto;
        height: auto;
      }
    }
  </style>
</head>
<body>
<header>
  <h1>Reasoning Substrate v1 – Universal Substrate Demo</h1>
  <p>One RS operator graph, many worlds: compiler, telecom, banking, networking.</p>
</header>
<div class="banner">
  <strong>RS v1 operators act as a buffer between semantic instructions and hardware/system‑legible typed transitions.</strong>
  This demo shows how RS converts meaning → typed operators → backend‑specific execution and envelopes.
</div>

<main>
  <!-- LEFT: INPUT / SCENARIO -->
  <section>
    <header>
      <h2>Input</h2>
      <span>Scenario &amp; semantic instructions</span>
    </header>
    <div class="section-body">
      <div class="row">
        <span>Scenario:</span>
        <select id="scenarioSelect">
          <option value="compiler">Universal Compiler (DSL)</option>
          <option value="telecom">Telecom Legacy Envelope</option>
          <option value="banking">Banking Legacy Envelope</option>
          <option value="networking">Networking Legacy Envelope</option>
        </select>
        <button id="loadExampleBtn" class="secondary">Load Example</button>
      </div>
      <textarea id="inputArea" spellcheck="false"></textarea>
      <div class="row">
        <button id="runBtn">Run through RS</button>
        <span>RS will parse → build operator graph → emit backend view.</span>
      </div>
      <div id="inputStatus" class="status"></div>
    </div>
  </section>

  <!-- CENTER: RS GRAPH -->
  <section>
    <header>
      <h2>RS Graph</h2>
      <span>Typed operator transitions (substrate)</span>
    </header>
    <div class="section-body">
      <div class="graph-canvas" id="graphCanvas"></div>
      <div class="legend">
        <span><span class="legend-dot"></span> RS operator node</span>
        <span><span class="legend-dot edge"></span> Typed transition</span>
      </div>
      <div class="row">
        <button id="playBtn" class="secondary">Play operator flow</button>
        <span id="graphInfo"></span>
      </div>
      <div class="explanation" id="explanationBox"></div>
    </div>
  </section>

  <!-- RIGHT: BACKEND VIEW -->
  <section>
    <header>
      <h2>Backend View</h2>
      <span>How RS presents to systems</span>
    </header>
    <div class="section-body">
      <pre id="backendOutput"></pre>
    </div>
  </section>
</main>

<script>
  // --- RS IR model (toy) -----------------------------------------------------
  // RS node: { id, op, args, type }
  // RS graph: { nodes: [...], edges: [{from, to}] }

  function parseScenarioToRS(scenario, text) {
    const lines = text
      .split("\n")
      .map(l => l.trim())
      .filter(l => l && !l.startsWith("#"));

    if (!lines.length) {
      throw new Error("No semantic instructions found.");
    }

    const nodes = [];
    const edges = [];
    let lastId = null;
    let idCounter = 1;

    function addNode(op, args, type) {
      const node = { id: "n" + idCounter++, op, args, type };
      nodes.push(node);
      if (lastId) edges.push({ from: lastId, to: node.id });
      lastId = node.id;
      return node;
    }

    if (scenario === "compiler") {
      // DSL: LOAD A, ADD B, MUL 0.5, THRESH 0.7, ROUTE OUT1
      for (const line of lines) {
        const parts = line.split(/\s+/);
        const cmd = parts[0].toUpperCase();
        if (cmd === "LOAD") {
          if (parts.length !== 2) throw new Error("LOAD expects 1 argument");
          addNode("LOAD", { src: parts[1] }, "tensor");
        } else if (cmd === "ADD") {
          if (parts.length !== 2) throw new Error("ADD expects 1 argument");
          addNode("ADD", { value: parts[1] }, "tensor");
        } else if (cmd === "MUL") {
          if (parts.length !== 2) throw new Error("MUL expects 1 argument");
          const factor = parseFloat(parts[1]);
          if (Number.isNaN(factor)) throw new Error("MUL expects numeric factor");
          addNode("MUL", { factor }, "tensor");
        } else if (cmd === "THRESH") {
          if (parts.length !== 2) throw new Error("THRESH expects 1 argument");
          const t = parseFloat(parts[1]);
          if (Number.isNaN(t)) throw new Error("THRESH expects numeric threshold");
          addNode("THRESH", { threshold: t }, "mask");
        } else if (cmd === "ROUTE") {
          if (parts.length !== 2) throw new Error("ROUTE expects 1 argument");
          addNode("ROUTE", { target: parts[1] }, "route");
        } else {
          throw new Error("Unknown DSL command: " + cmd);
        }
      }
    } else if (scenario === "telecom") {
      // Very simple mapping of telecom-ish lines into RS ops
      // e.g. DIAL 5551234, AUTH IMSI123, SIGNAL ALERT, ROUTE SWITCH_A
      for (const line of lines) {
        const parts = line.split(/\s+/);
        const cmd = parts[0].toUpperCase();
        if (cmd === "DIAL") {
          addNode("LOAD_CALL", { number: parts.slice(1).join(" ") }, "call");
        } else if (cmd === "AUTH") {
          addNode("AUTH_SUBSCRIBER", { id: parts.slice(1).join(" ") }, "auth");
        } else if (cmd === "SIGNAL") {
          addNode("SIGNAL_EVENT", { event: parts.slice(1).join(" ") }, "signal");
        } else if (cmd === "ROUTE") {
          addNode("ROUTE_SWITCH", { target: parts.slice(1).join(" ") }, "route");
        } else {
          addNode("ANNOTATE", { text: line }, "meta");
        }
      }
    } else if (scenario === "banking") {
      // e.g. LOAD_ACCOUNT 123, DEBIT 50, CREDIT 20, APPLY_RULE AML_CHECK, ROUTE CLEARING
      for (const line of lines) {
        const parts = line.split(/\s+/);
        const cmd = parts[0].toUpperCase();
        if (cmd === "LOAD_ACCOUNT") {
          addNode("LOAD_ACCOUNT", { id: parts[1] }, "account");
        } else if (cmd === "DEBIT") {
          addNode("DEBIT", { amount: parseFloat(parts[1]) }, "txn");
        } else if (cmd === "CREDIT") {
          addNode("CREDIT", { amount: parseFloat(parts[1]) }, "txn");
        } else if (cmd === "APPLY_RULE") {
          addNode("APPLY_RULE", { rule: parts.slice(1).join(" ") }, "rule");
        } else if (cmd === "ROUTE") {
          addNode("ROUTE_LEDGER", { target: parts.slice(1).join(" ") }, "route");
        } else {
          addNode("ANNOTATE", { text: line }, "meta");
        }
      }
    } else if (scenario === "networking") {
      // e.g. MATCH SRC=10.0.0.1, MATCH DST=10.0.0.2, INSPECT DPI, ROUTE VLAN_10, DROP
      for (const line of lines) {
        const parts = line.split(/\s+/);
        const cmd = parts[0].toUpperCase();
        if (cmd === "MATCH") {
          addNode("MATCH", { expr: parts.slice(1).join(" ") }, "filter");
        } else if (cmd === "INSPECT") {
          addNode("INSPECT", { mode: parts.slice(1).join(" ") }, "inspect");
        } else if (cmd === "ROUTE") {
          addNode("ROUTE_PATH", { target: parts.slice(1).join(" ") }, "route");
        } else if (cmd === "DROP") {
          addNode("DROP", {}, "action");
        } else {
          addNode("ANNOTATE", { text: line }, "meta");
        }
      }
    }

    return { nodes, edges };
  }

  // --- Backend views ---------------------------------------------------------

  function backendForScenario(scenario, rs) {
    if (scenario === "compiler") {
      const lines = [];
      lines.push("# RS → Python backend (illustrative)");
      lines.push("def rs_program(inputs):");
      lines.push("    x = None");
      for (const node of rs.nodes) {
        if (node.op === "LOAD") {
          lines.push(`    x = inputs["${node.args.src}"]  # LOAD`);
        } else if (node.op === "ADD") {
          lines.push(`    x = x + inputs["${node.args.value}"]  # ADD`);
        } else if (node.op === "MUL") {
          lines.push(`    x = x * ${node.args.factor}  # MUL`);
        } else if (node.op === "THRESH") {
          lines.push(`    mask = (x > ${node.args.threshold})  # THRESH`);
        } else if (node.op === "ROUTE") {
          lines.push(`    outputs = {"${node.args.target}": x}  # ROUTE`);
        }
      }
      lines.push("    return locals()");
      return lines.join("\n");
    }

    if (scenario === "telecom") {
      const lines = [];
      lines.push("# RS → Telecom legacy envelope (illustrative)");
      let idx = 0;
      for (const node of rs.nodes) {
        idx++;
        if (node.op === "LOAD_CALL") {
          lines.push(`${idx}. MAP_READ_CALL number=${node.args.number}`);
        } else if (node.op === "AUTH_SUBSCRIBER") {
          lines.push(`${idx}. MAP_AUTH_SUBSCRIBER id=${node.args.id}`);
        } else if (node.op === "SIGNAL_EVENT") {
          lines.push(`${idx}. SS7_SIGNAL event=${node.args.event}`);
        } else if (node.op === "ROUTE_SWITCH") {
          lines.push(`${idx}. ROUTE_TO_SWITCH target=${node.args.target}`);
        } else if (node.op === "ANNOTATE") {
          lines.push(`${idx}. # NOTE: ${node.args.text}`);
        }
      }
      return lines.join("\n");
    }

    if (scenario === "banking") {
      const lines = [];
      lines.push("# RS → Banking legacy envelope (illustrative)");
      let idx = 0;
      for (const node of rs.nodes) {
        idx++;
        if (node.op === "LOAD_ACCOUNT") {
          lines.push(`${idx}. COBOL_READ_ACCOUNT id=${node.args.id}`);
        } else if (node.op === "DEBIT") {
          lines.push(`${idx}. COBOL_DEBIT amount=${node.args.amount}`);
        } else if (node.op === "CREDIT") {
          lines.push(`${idx}. COBOL_CREDIT amount=${node.args.amount}`);
        } else if (node.op === "APPLY_RULE") {
          lines.push(`${idx}. RULE_ENGINE_APPLY rule=${node.args.rule}`);
        } else if (node.op === "ROUTE_LEDGER") {
          lines.push(`${idx}. ROUTE_TO_LEDGER target=${node.args.target}`);
        } else if (node.op === "ANNOTATE") {
          lines.push(`${idx}. # NOTE: ${node.args.text}`);
        }
      }
      return lines.join("\n");
    }

    if (scenario === "networking") {
      const lines = [];
      lines.push("# RS → Networking control plane envelope (illustrative)");
      let idx = 0;
      for (const node of rs.nodes) {
        idx++;
        if (node.op === "MATCH") {
          lines.push(`${idx}. ACL_MATCH ${node.args.expr}`);
        } else if (node.op === "INSPECT") {
          lines.push(`${idx}. DPI_INSPECT mode=${node.args.mode}`);
        } else if (node.op === "ROUTE_PATH") {
          lines.push(`${idx}. ROUTE_VIA ${node.args.target}`);
        } else if (node.op === "DROP") {
          lines.push(`${idx}. ACTION_DROP`);
        } else if (node.op === "ANNOTATE") {
          lines.push(`${idx}. # NOTE: ${node.args.text}`);
        }
      }
      return lines.join("\n");
    }

    return "# No backend view available.";
  }

  // --- Explanation text ------------------------------------------------------

  function explanationForScenario(scenario) {
    if (scenario === "compiler") {
      return (
        "<strong>Compiler mode:</strong> In this demo, RS v1 is translating semantic DSL instructions into typed operators " +
        "that can target any backend. You are seeing RS act as a universal intermediate representation — the stable " +
        "substrate between human‑level meaning and machine‑level execution."
      );
    }
    if (scenario === "telecom") {
      return (
        "<strong>Telecom envelope mode:</strong> Here RS v1 is normalizing legacy signaling (DIAL, AUTH, SIGNAL, ROUTE) " +
        "into typed operators. The RS graph absorbs telecom semantics and emits a clean operator stream that a legacy " +
        "SS7/MAP/SIP stack could consume, without changing the substrate."
      );
    }
    if (scenario === "banking") {
      return (
        "<strong>Banking envelope mode:</strong> RS v1 is wrapping COBOL‑style account operations and rule‑engine logic " +
        "into typed transitions. The same substrate that powers a compiler can also unify mainframes, batch systems, " +
        "and modern compute under one operator graph."
      );
    }
    if (scenario === "networking") {
      return (
        "<strong>Networking envelope mode:</strong> RS v1 is converting routing, packet‑matching, and inspection semantics " +
        "into typed operators. This illustrates RS as a universal control plane that can sit above heterogeneous " +
        "network devices while preserving a single reasoning substrate."
      );
    }
    return "";
  }

  // --- Graph visualizer ------------------------------------------------------

  function renderGraph(rs) {
    const canvas = document.getElementById("graphCanvas");
    canvas.innerHTML = "";
    const info = document.getElementById("graphInfo");
    if (!rs || !rs.nodes.length) {
      info.textContent = "";
      return;
    }

    const w = canvas.clientWidth || 300;
    const h = canvas.clientHeight || 200;
    const marginX = 40;
    const stepX = (w - 2 * marginX) / Math.max(1, rs.nodes.length - 1);
    const positions = {};

    rs.nodes.forEach((node, i) => {
      const x = marginX + i * stepX;
      const y = h / 2;
      positions[node.id] = { x, y };
    });

    rs.edges.forEach(edge => {
      const from = positions[edge.from];
      const to = positions[edge.to];
      if (!from || !to) return;
      const edgeDiv = document.createElement("div");
      edgeDiv.className = "edge";
      const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
      const dx = to.x - from.x;
      const midX = from.x + dx / 2;
      const d = `M ${from.x} ${from.y} C ${midX} ${from.y - 30}, ${midX} ${to.y + 30}, ${to.x} ${to.y}`;
      path.setAttribute("d", d);
      svg.appendChild(path);
      edgeDiv.appendChild(svg);
      canvas.appendChild(edgeDiv);
    });

    rs.nodes.forEach(node => {
      const pos = positions[node.id];
      const div = document.createElement("div");
      div.className = "node";
      div.dataset.nodeId = node.id;
      div.style.left = (pos.x - 30) + "px";
      div.style.top = (pos.y - 14) + "px";
      div.textContent = node.op;
      canvas.appendChild(div);
    });

    info.textContent = `${rs.nodes.length} operators, ${rs.edges.length} transitions`;
  }

  function playAnimation(rs) {
    if (!rs || !rs.nodes.length) return;
    const nodes = Array.from(document.querySelectorAll(".node"));
    nodes.forEach(n => n.classList.remove("active"));
    let i = 0;
    function step() {
      nodes.forEach(n => n.classList.remove("active"));
      if (i < rs.nodes.length) {
        const id = rs.nodes[i].id;
        const el = nodes.find(n => n.dataset.nodeId === id);
        if (el) el.classList.add("active");
        i++;
        setTimeout(step, 450);
      }
    }
    step();
  }

  // --- Wiring ---------------------------------------------------------------

  const scenarioSelect = document.getElementById("scenarioSelect");
  const loadExampleBtn = document.getElementById("loadExampleBtn");
  const runBtn = document.getElementById("runBtn");
  const playBtn = document.getElementById("playBtn");
  const inputArea = document.getElementById("inputArea");
  const inputStatus = document.getElementById("inputStatus");
  const backendOutput = document.getElementById("backendOutput");
  const explanationBox = document.getElementById("explanationBox");

  let currentRS = null;

  function loadExample() {
    const scenario = scenarioSelect.value;
    if (scenario === "compiler") {
      inputArea.value = [
        "# Universal compiler DSL example",
        "LOAD A",
        "ADD B",
        "MUL 0.5",
        "THRESH 0.7",
        "ROUTE OUT1"
      ].join("\n");
    } else if (scenario === "telecom") {
      inputArea.value = [
        "# Telecom envelope example",
        "DIAL 555-1234",
        "AUTH IMSI-00101",
        "SIGNAL ALERTING",
        "ROUTE SWITCH_A"
      ].join("\n");
    } else if (scenario === "banking") {
      inputArea.value = [
        "# Banking envelope example",
        "LOAD_ACCOUNT 123456",
        "DEBIT 50.00",
        "CREDIT 10.00",
        "APPLY_RULE AML_CHECK",
        "ROUTE CLEARING_HOUSE"
      ].join("\n");
    } else if (scenario === "networking") {
      inputArea.value = [
        "# Networking envelope example",
        "MATCH SRC=10.0.0.1",
        "MATCH DST=10.0.0.2",
        "INSPECT DPI",
        "ROUTE VLAN_10",
        "DROP"
      ].join("\n");
    }
    inputStatus.textContent = "";
    inputStatus.className = "status";
  }

  loadExampleBtn.addEventListener("click", loadExample);
  scenarioSelect.addEventListener("change", loadExample);

  runBtn.addEventListener("click", () => {
    const scenario = scenarioSelect.value;
    const text = inputArea.value;
    try {
      const rs = parseScenarioToRS(scenario, text);
      currentRS = rs;
      renderGraph(rs);
      backendOutput.textContent = backendForScenario(scenario, rs);
      explanationBox.innerHTML = explanationForScenario(scenario) +
        "<br><br><em>In this demo, RS v1 is acting as a buffer between semantic content and backend‑specific " +
        "representations, without changing the substrate itself.</em>";
      inputStatus.textContent = "Semantic instructions compiled into RS operator graph.";
      inputStatus.className = "status ok";
    } catch (e) {
      currentRS = null;
      document.getElementById("graphCanvas").innerHTML = "";
      document.getElementById("graphInfo").textContent = "";
      backendOutput.textContent = "";
      explanationBox.textContent = "";
      inputStatus.textContent = e.message;
      inputStatus.className = "status err";
    }
  });

  playBtn.addEventListener("click", () => {
    if (currentRS) playAnimation(currentRS);
  });

  // Initial state
  loadExample();
  runBtn.click();
</script>
</body>
</html>

RS·03 — RS v1 — POP-LITE Processor Optimizer

Simulates CPU/GPU/memory/thermal/battery with four plan modes. RS substrate governs hardware state toward low-entropy configurations.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>POP‑LITE Toy Demo</title>
  <style>
    body { font-family: system-ui, sans-serif; background:#0b0c10; color:#eaeaea; margin:0; padding:20px; }
    h1 { margin-top:0; }
    .container { display:flex; gap:20px; flex-wrap:wrap; }
    .panel { background:#151720; padding:16px; border-radius:8px; flex:1 1 260px; min-width:260px; }
    .label { font-size:12px; text-transform:uppercase; letter-spacing:0.08em; color:#9fa4c0; }
    .value { font-size:24px; margin:4px 0 8px; }
    .plan { font-weight:600; color:#ffd166; }
    .bar-wrap { background:#222533; border-radius:4px; height:10px; overflow:hidden; }
    .bar { height:100%; background:#4cc9f0; width:0%; transition:width 0.2s ease-out; }
    button { margin-top:10px; padding:8px 14px; border-radius:4px; border:none; cursor:pointer; background:#4cc9f0; color:#05060a; font-weight:600; }
    button:disabled { opacity:0.4; cursor:default; }
    .log { font-size:11px; max-height:160px; overflow:auto; background:#10111a; padding:8px; border-radius:6px; }
    .tag { display:inline-block; padding:2px 6px; border-radius:4px; font-size:10px; margin-right:4px; }
    .tag-balanced { background:#264653; color:#e9ecef; }
    .tag-perf { background:#2a9d8f; color:#e9ecef; }
    .tag-eco { background:#e76f51; color:#fff; }
    .tag-lat { background:#f4a261; color:#05060a; }
  </style>
</head>
<body>
  <h1>POP‑LITE Toy Demo</h1>
  <p style="max-width:640px;">
    This toy simulates a “laptop” with <b>CPU</b>, <b>GPU</b>, <b>Memory</b>, <b>Thermals</b>, and <b>Battery</b>.
    POP‑LITE watches the state, chooses a plan, and stabilizes the system toward a smooth, low‑entropy regime.
  </p>

  <div class="container">
    <div class="panel">
      <div class="label">Current Plan</div>
      <div class="value plan" id="planName">—</div>
      <div>
        <span class="tag tag-balanced">BALANCED</span>
        <span class="tag tag-perf">PERFORMANCE</span>
        <span class="tag tag-eco">ECO</span>
        <span class="tag tag-lat">LATENCY</span>
      </div>
      <button id="startBtn">Start POP‑LITE</button>
      <button id="spikeBtn">Inject Load Spike</button>
    </div>

    <div class="panel">
      <div class="label">CPU Utilization</div>
      <div class="value" id="cpuVal">0%</div>
      <div class="bar-wrap"><div class="bar" id="cpuBar"></div></div>

      <div class="label" style="margin-top:12px;">GPU Utilization</div>
      <div class="value" id="gpuVal">0%</div>
      <div class="bar-wrap"><div class="bar" id="gpuBar"></div></div>

      <div class="label" style="margin-top:12px;">Memory Pressure</div>
      <div class="value" id="memVal">0%</div>
      <div class="bar-wrap"><div class="bar" id="memBar"></div></div>
    </div>

    <div class="panel">
      <div class="label">Thermals (CPU / GPU)</div>
      <div class="value" id="thermVal">0°C / 0°C</div>

      <div class="label" style="margin-top:12px;">Battery Level</div>
      <div class="value" id="batVal">0%</div>
      <div class="bar-wrap"><div class="bar" id="batBar" style="background:#95d5b2;"></div></div>

      <div class="label" style="margin-top:16px;">Event Log</div>
      <div class="log" id="logBox"></div>
    </div>
  </div>

  <script>
    // --- Simple helpers ---
    const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
    const lerp = (a, b, t) => a + (b - a) * t;

    function smooth(prev, next, alpha = 0.2) {
      return lerp(prev, next, alpha);
    }

    // --- Simulated system state ---
    let state = {
      CPU: { utilization: 0.25 },
      GPU: { utilization: 0.20 },
      MEMORY: { pressure: 0.30 },
      THERMALS: { cpu_temp: 55, gpu_temp: 50 },
      BATTERY: { discharge_rate: 0.10, level: 0.85 }
    };

    let previousPlan = null;
    let running = false;
    let spike = false;

    const INTERVAL_MS = 200;
    const SWITCH_THRESHOLD = 0.12;

    // --- POP-LITE core (toy) ---

    function F_lite(s) {
      const p = {};
      p.CPU = { utilization: smooth(s.CPU.utilization, s.CPU.utilization + (spike ? 0.3 : 0), 0.3) };
      p.GPU = { utilization: smooth(s.GPU.utilization, s.GPU.utilization + (spike ? 0.4 : 0), 0.3) };
      p.MEMORY = { pressure: smooth(s.MEMORY.pressure, s.MEMORY.pressure + (spike ? 0.2 : 0), 0.3) };
      p.THERMALS = {
        cpu_temp: smooth(s.THERMALS.cpu_temp, 50 + p.CPU.utilization * 60, 0.2),
        gpu_temp: smooth(s.THERMALS.gpu_temp, 45 + p.GPU.utilization * 60, 0.2)
      };
      p.BATTERY = {
        discharge_rate: smooth(s.BATTERY.discharge_rate, 0.05 + (p.CPU.utilization + p.GPU.utilization) * 0.3, 0.2),
        level: clamp(s.BATTERY.level - p.BATTERY.discharge_rate * 0.002, 0, 1)
      };
      return p;
    }

    function generatePlansLite() {
      return [
        { name: "BALANCED", cpu_mode: "balanced", gpu_mode: "adaptive", memory_mode: "normal", battery_mode: "balanced" },
        { name: "PERFORMANCE", cpu_mode: "performance", gpu_mode: "max", memory_mode: "normal", battery_mode: "performance" },
        { name: "ECO", cpu_mode: "powersave", gpu_mode: "powersave", memory_mode: "compact", battery_mode: "eco" },
        { name: "LATENCY_PRIORITY", cpu_mode: "burst", gpu_mode: "burst", memory_mode: "normal", battery_mode: "balanced" }
      ];
    }

    function estimateLatencyCost(plan, p) {
      const util = (p.CPU.utilization + p.GPU.utilization) / 2;
      if (plan.name === "LATENCY_PRIORITY") return 0.2 + util * 0.3;
      if (plan.name === "PERFORMANCE") return 0.3 + util * 0.2;
      if (plan.name === "BALANCED") return 0.4 + util * 0.2;
      if (plan.name === "ECO") return 0.6 + util * 0.1;
      return 0.5;
    }

    function estimateThermalRisk(plan, p) {
      const t = (p.THERMALS.cpu_temp + p.THERMALS.gpu_temp) / 2;
      const norm = clamp((t - 50) / 40, 0, 1);
      if (plan.name === "PERFORMANCE" || plan.name === "LATENCY_PRIORITY") return 0.3 + norm * 0.7;
      if (plan.name === "BALANCED") return 0.2 + norm * 0.6;
      if (plan.name === "ECO") return 0.1 + norm * 0.4;
      return 0.5;
    }

    function estimateBatteryCost(plan, p) {
      const d = p.BATTERY.discharge_rate;
      if (plan.name === "PERFORMANCE" || plan.name === "LATENCY_PRIORITY") return 0.4 + d * 1.0;
      if (plan.name === "BALANCED") return 0.3 + d * 0.7;
      if (plan.name === "ECO") return 0.1 + d * 0.4;
      return 0.5;
    }

    function estimateMemoryRisk(plan, p) {
      const m = p.MEMORY.pressure;
      if (plan.name === "ECO") return 0.2 + m * 0.4;
      if (plan.name === "BALANCED") return 0.3 + m * 0.5;
      if (plan.name === "PERFORMANCE" || plan.name === "LATENCY_PRIORITY") return 0.4 + m * 0.6;
      return 0.5;
    }

    function scorePlansLite(plans, p) {
      return plans.map(plan => {
        const latency = estimateLatencyCost(plan, p);
        const therm = estimateThermalRisk(plan, p);
        const batt = estimateBatteryCost(plan, p);
        const mem = estimateMemoryRisk(plan, p);
        const energy = 1.0 * latency + 1.0 * therm + 0.8 * batt + 0.7 * mem;
        return { plan, energy };
      }).sort((a, b) => a.energy - b.energy);
    }

    function collapseLite(scored, prev) {
      const best = scored[0];
      if (!prev) return best.plan;

      const prevEntry = scored.find(x => x.plan.name === prev.name) || best;
      const gap = best.energy - prevEntry.energy;

      if (gap < -SWITCH_THRESHOLD) return best.plan;
      return prev;
    }

    function applyLite(plan) {
      // In the toy, we don't actually call OS APIs.
      log(`POP‑LITE chose plan: ${plan.name}`);
    }

    function safetyOkLite(s) {
      if (s.THERMALS.cpu_temp > 95 || s.THERMALS.gpu_temp > 95) {
        log("Safety: thermal limit reached → forcing cool‑down.");
        return false;
      }
      if (s.MEMORY.pressure > 0.98) {
        log("Safety: memory pressure critical → recovery mode.");
        return false;
      }
      return true;
    }

    // --- UI wiring ---

    const cpuVal = document.getElementById("cpuVal");
    const gpuVal = document.getElementById("gpuVal");
    const memVal = document.getElementById("memVal");
    const thermVal = document.getElementById("thermVal");
    const batVal = document.getElementById("batVal");
    const cpuBar = document.getElementById("cpuBar");
    const gpuBar = document.getElementById("gpuBar");
    const memBar = document.getElementById("memBar");
    const batBar = document.getElementById("batBar");
    const planName = document.getElementById("planName");
    const logBox = document.getElementById("logBox");
    const startBtn = document.getElementById("startBtn");
    const spikeBtn = document.getElementById("spikeBtn");

    function log(msg) {
      const ts = new Date().toLocaleTimeString();
      logBox.innerHTML = `[${ts}] ${msg}<br>` + logBox.innerHTML;
    }

    function render() {
      cpuVal.textContent = Math.round(state.CPU.utilization * 100) + "%";
      gpuVal.textContent = Math.round(state.GPU.utilization * 100) + "%";
      memVal.textContent = Math.round(state.MEMORY.pressure * 100) + "%";
      thermVal.textContent = `${Math.round(state.THERMALS.cpu_temp)}°C / ${Math.round(state.THERMALS.gpu_temp)}°C`;
      batVal.textContent = Math.round(state.BATTERY.level * 100) + "%";

      cpuBar.style.width = Math.round(state.CPU.utilization * 100) + "%";
      gpuBar.style.width = Math.round(state.GPU.utilization * 100) + "%";
      memBar.style.width = Math.round(state.MEMORY.pressure * 100) + "%";
      batBar.style.width = Math.round(state.BATTERY.level * 100) + "%";
    }

    function tick() {
      if (!running) return;

      // evolve state a bit (noise)
      state.CPU.utilization = clamp(state.CPU.utilization + (Math.random() - 0.5) * 0.05, 0, 1);
      state.GPU.utilization = clamp(state.GPU.utilization + (Math.random() - 0.5) * 0.05, 0, 1);
      state.MEMORY.pressure = clamp(state.MEMORY.pressure + (Math.random() - 0.5) * 0.03, 0, 1);

      const predicted = F_lite(state);
      if (!safetyOkLite(predicted)) {
        // crude cool-down
        state.THERMALS.cpu_temp = lerp(state.THERMALS.cpu_temp, 55, 0.3);
        state.THERMALS.gpu_temp = lerp(state.THERMALS.gpu_temp, 50, 0.3);
        spike = false;
        render();
        setTimeout(tick, INTERVAL_MS);
        return;
      }

      const plans = generatePlansLite();
      const scored = scorePlansLite(plans, predicted);
      const chosen = collapseLite(scored, previousPlan);
      previousPlan = chosen;
      applyLite(chosen);
      planName.textContent = chosen.name;

      // move state toward predicted (stabilization)
      state = {
        CPU: { utilization: predicted.CPU.utilization },
        GPU: { utilization: predicted.GPU.utilization },
        MEMORY: { pressure: predicted.MEMORY.pressure },
        THERMALS: {
          cpu_temp: predicted.THERMALS.cpu_temp,
          gpu_temp: predicted.THERMALS.gpu_temp
        },
        BATTERY: {
          discharge_rate: predicted.BATTERY.discharge_rate,
          level: predicted.BATTERY.level
        }
      };

      spike = false;
      render();
      setTimeout(tick, INTERVAL_MS);
    }

    startBtn.onclick = () => {
      if (running) return;
      running = true;
      startBtn.disabled = true;
      log("POP‑LITE started.");
      render();
      tick();
    };

    spikeBtn.onclick = () => {
      spike = true;
      log("Injected synthetic load spike (CPU/GPU/MEM).");
    };

    render();
  </script>
</body>
</html>

HEG·01 — HEG — Segmentation Edge Cases

Stresses the SEGMENT operator with nested intents, abrupt topic shifts, and contradictory instructions.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body{background:#050608;color:#e4f4e4;font-family:"IBM Plex Mono",Menlo,"Courier New",monospace;padding:20px;font-size:0.82rem;line-height:1.65;}
h1{color:#ffbf40;font-size:1.2rem;margin-bottom:0.3rem;letter-spacing:0.08em;}
h2{color:#ffd27f;font-size:1rem;margin-top:1.2rem;letter-spacing:0.06em;}
h3{color:#f1a85a;font-size:0.9rem;margin-top:1rem;}
label{color:#ffb86c;font-size:0.82rem;}
button{background:#111;color:#ffbf40;border:1px solid #444;padding:7px 12px;margin:4px 4px 8px 0;cursor:pointer;border-radius:3px;font-size:0.85rem;font-family:inherit;}
button:hover{background:#181008;border-color:#ffb86c;}
input,select,textarea{background:#0b0d10;color:#ffb86c;border:1px solid #3a2614;padding:4px 8px;font-family:inherit;font-size:0.8rem;border-radius:2px;}
pre,#output{background:#0b0d10;border:1px solid #222;padding:10px;max-height:420px;overflow:auto;font-size:0.78rem;color:#ffb86c;}
.small{font-size:0.82rem;color:#a8bfa8;}
.badge{font-size:0.78rem;color:#c0ffc0;margin-left:8px;border:1px solid #3a2614;padding:2px 6px;border-radius:2px;}
table{border-collapse:collapse;width:100%;margin-top:0.5rem;}
th{color:#ffbf40;border-bottom:1px solid #3a2614;padding:4px 8px;text-align:left;font-size:0.78rem;}
td{color:#e4f4e4;border-bottom:1px solid #1a1209;padding:4px 8px;font-size:0.78rem;}
</style>
<meta charset="UTF-8">
<title>HEG Toy 2 – Segmentation Edge Cases</title>

</head>
<body>
<div class="app-container">
  <!-- LEFT: Input -->
  <div class="pane left-pane">
    <div class="static-panel">
      <div class="static-header">HEG Toy 2 – Segmentation Edge Cases</div>
      <div class="static-label">
        Single operator under stress: SEGMENT. Show where boundaries are hard and why they matter.
      </div>
      <textarea id="inputText" placeholder="Example:
Okay, listen: first, cancel the trip—actually, no, keep the flights but not the hotel, and while you’re at it, can you also check if there’s a safer route? I mean, if it’s not too risky, we still go."></textarea>
      <div class="section-title">Presets</div>
      <button class="preset-btn" data-preset="nested">Nested Intent + Reversal</button>
      <button class="preset-btn" data-preset="topicShift">Mid-sentence Topic Shift</button>
      <button class="preset-btn" data-preset="contradict">Contradictory Directives</button>
      <div class="section-title">Run</div>
      <button id="runButton">Run Segmentation</button>
      <div class="small-note">
        Goal: make it obvious that segmentation is non-trivial and upstream of CAP quality.
      </div>
    </div>
    <div class="dynamic-panel" id="traceArea"></div>
  </div>

  <!-- RIGHT: Segments + Commentary -->
  <div class="pane right-pane">
    <div class="static-panel">
      <div class="static-header">Segments & Commentary</div>
      <div class="static-label">
        Left: raw trace of the segmentation operator. Right: segments with notes on why the cut matters.
      </div>
    </div>
    <div class="dynamic-panel" id="segmentsPanel">
      <div class="section-title">Segments</div>
      <div id="segmentsContainer"></div>
    </div>
  </div>
</div>

<script>
const PRESETS = {
  nested: `Okay, listen: first, cancel the trip—actually, no, keep the flights but not the hotel, and while you’re at it, can you also check if there’s a safer route? I mean, if it’s not too risky, we still go.`,
  topicShift: `I love this plan, but the budget is a problem, and by the way, did you ever fix that login issue because it’s blocking the rollout.`,
  contradict: `Please lock in the most aggressive timeline you can, but also don’t rush anything and make sure nobody feels pressured.`
};

const inputTextEl = document.getElementById("inputText");
const runButtonEl = document.getElementById("runButton");
const traceAreaEl = document.getElementById("traceArea");
const segmentsContainerEl = document.getElementById("segmentsContainer");
const presetButtons = document.querySelectorAll(".preset-btn");

function appendTrace(text) {
  const div = document.createElement("div");
  div.className = "trace-line";
  div.textContent = text;
  traceAreaEl.appendChild(div);
  traceAreaEl.scrollTop = traceAreaEl.scrollHeight;
}

function clearUI() {
  traceAreaEl.innerHTML = "";
  segmentsContainerEl.innerHTML = "";
}

function segment(text) {
  // Deliberately simple but visible: sentence + clause splitting
  const raw = text
    .split(/[\n]+/)
    .map(l => l.trim())
    .filter(l => l.length > 0)
    .flatMap(l => l.split(/(?<=[.?!])\s+/));

  const segments = [];
  raw.forEach(sentence => {
    const clauses = sentence.split(/[,;—-](?=\s|$)/);
    clauses.forEach(c => {
      const s = c.trim();
      if (s.length) segments.push(s);
    });
  });
  return segments;
}

function annotateSegment(seg) {
  const lower = seg.toLowerCase();
  const notes = [];

  if (lower.includes("actually") || lower.includes("no, keep")) {
    notes.push("Reversal / correction inside same utterance. Boundary choice affects which intent dominates.");
  }
  if (lower.includes("but")) {
    notes.push("Contrastive 'but' – often a semantic pivot. Downstream CAPs may treat pre/post differently.");
  }
  if (lower.includes("and by the way") || lower.includes("by the way")) {
    notes.push("Topic shift marker. Good segmentation isolates the new thread.");
  }
  if (lower.includes("if it’s not too risky") || lower.includes("if it's not too risky")) {
    notes.push("Conditional clause. Whether it’s its own segment changes how constraints are registered.");
  }
  if (notes.length === 0) {
    notes.push("No special heuristic fired. Still a candidate CAP boundary.");
  }
  return notes;
}

function renderSegments(segments) {
  segments.forEach((seg, idx) => {
    const card = document.createElement("div");
    card.className = "segment-card";
    const notes = annotateSegment(seg);
    card.textContent =
      "Segment #" + (idx + 1) + ":\n" +
      seg + "\n\n" +
      "Why this cut matters:\n- " + notes.join("\n- ");
    segmentsContainerEl.appendChild(card);
  });
}

function runSegmentation() {
  clearUI();
  const text = inputTextEl.value.trim();
  if (!text) {
    appendTrace("[ERROR] No input text.");
    return;
  }
  appendTrace("[INPUT] " + text);
  const segments = segment(text);
  appendTrace("[SEGMENT] Produced " + segments.length + " segments.");
  segments.forEach((s, i) => appendTrace("  [" + (i+1) + "] " + s));
  renderSegments(segments);
}

runButtonEl.addEventListener("click", runSegmentation);

presetButtons.forEach(btn => {
  btn.addEventListener("click", () => {
    const key = btn.getAttribute("data-preset");
    inputTextEl.value = PRESETS[key] || "";
  });
});
</script>
</body>
</html>

HEG·02 — HEG — Act Classification Ambiguity

Targets the ACT operator boundary between COMMAND, ASK, and ASSERT. Exposes scoring heuristics used to disambiguate intent type.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body{background:#050608;color:#e4f4e4;font-family:"IBM Plex Mono",Menlo,"Courier New",monospace;padding:20px;font-size:0.82rem;line-height:1.65;}
h1{color:#ffbf40;font-size:1.2rem;margin-bottom:0.3rem;letter-spacing:0.08em;}
h2{color:#ffd27f;font-size:1rem;margin-top:1.2rem;letter-spacing:0.06em;}
h3{color:#f1a85a;font-size:0.9rem;margin-top:1rem;}
label{color:#ffb86c;font-size:0.82rem;}
button{background:#111;color:#ffbf40;border:1px solid #444;padding:7px 12px;margin:4px 4px 8px 0;cursor:pointer;border-radius:3px;font-size:0.85rem;font-family:inherit;}
button:hover{background:#181008;border-color:#ffb86c;}
input,select,textarea{background:#0b0d10;color:#ffb86c;border:1px solid #3a2614;padding:4px 8px;font-family:inherit;font-size:0.8rem;border-radius:2px;}
pre,#output{background:#0b0d10;border:1px solid #222;padding:10px;max-height:420px;overflow:auto;font-size:0.78rem;color:#ffb86c;}
.small{font-size:0.82rem;color:#a8bfa8;}
.badge{font-size:0.78rem;color:#c0ffc0;margin-left:8px;border:1px solid #3a2614;padding:2px 6px;border-radius:2px;}
table{border-collapse:collapse;width:100%;margin-top:0.5rem;}
th{color:#ffbf40;border-bottom:1px solid #3a2614;padding:4px 8px;text-align:left;font-size:0.78rem;}
td{color:#e4f4e4;border-bottom:1px solid #1a1209;padding:4px 8px;font-size:0.78rem;}
</style>
<meta charset="UTF-8">
<title>HEG Toy 3 – Act Classification Ambiguity</title>

</head>
<body>
<div class="app-container">
  <!-- LEFT: Input -->
  <div class="pane left-pane">
    <div class="static-panel">
      <div class="static-header">HEG Toy 3 – Act Classification Ambiguity</div>
      <div class="static-label">
        Single operator under stress: ACT. Show boundary cases between COMMAND / ASK / ASSERT.
      </div>
      <textarea id="inputText" placeholder="Example:
Maybe you could just send that over when you have a second."></textarea>
      <div class="section-title">Presets</div>
      <button class="preset-btn" data-preset="softCommand">Soft Command / Ask</button>
      <button class="preset-btn" data-preset="statementAsk">Statement That Feels Like a Question</button>
      <button class="preset-btn" data-preset="commandAssert">Command Disguised as Assertion</button>
      <div class="section-title">Run</div>
      <button id="runButton">Classify Act</button>
      <div class="small-note">
        Point: speech act type is underdetermined by syntax alone. We show the toy’s reasoning and scores.
      </div>
    </div>
    <div class="dynamic-panel" id="traceArea"></div>
  </div>

  <!-- RIGHT: Act + Reasoning -->
  <div class="pane right-pane">
    <div class="static-panel">
      <div class="static-header">Act Classification & Reasoning</div>
      <div class="static-label">
        We expose the scoring heuristic so the ambiguity is visible, not hidden.
      </div>
    </div>
    <div class="dynamic-panel" id="actsPanel">
      <div class="section-title">Act Decision</div>
      <div id="actContainer"></div>
    </div>
  </div>
</div>

<script>
const PRESETS = {
  softCommand: "Maybe you could just send that over when you have a second.",
  statementAsk: "It would be really helpful if that report were done by tomorrow.",
  commandAssert: "We’re going to have that finished by tomorrow, right."
};

const inputTextEl = document.getElementById("inputText");
const runButtonEl = document.getElementById("runButton");
const traceAreaEl = document.getElementById("traceArea");
const actContainerEl = document.getElementById("actContainer");
const presetButtons = document.querySelectorAll(".preset-btn");

function appendTrace(text) {
  const div = document.createElement("div");
  div.className = "trace-line";
  div.textContent = text;
  traceAreaEl.appendChild(div);
  traceAreaEl.scrollTop = traceAreaEl.scrollHeight;
}

function clearUI() {
  traceAreaEl.innerHTML = "";
  actContainerEl.innerHTML = "";
}

function classifyActWithScores(text) {
  const s = text.trim();
  const lower = s.toLowerCase();

  const scores = {
    COMMAND: 0.0,
    ASK: 0.0,
    ASSERT: 0.0,
    META: 0.0
  };

  // crude heuristics, but visible
  if (s.endsWith("?")) {
    scores.ASK += 0.6;
  }
  if (lower.startsWith("please ") || lower.includes("could you") || lower.includes("can you")) {
    scores.COMMAND += 0.5;
    scores.ASK += 0.3;
  }
  if (lower.includes("maybe you could") || lower.includes("it would be helpful if")) {
    scores.ASK += 0.4;
    scores.COMMAND += 0.3;
  }
  if (lower.includes("we’re going to") || lower.includes("we are going to")) {
    scores.ASSERT += 0.5;
    scores.COMMAND += 0.3;
  }
  if (lower.includes("i feel") || lower.includes("i think")) {
    scores.META += 0.5;
  }

  // baseline
  scores.ASSERT += 0.2;

  let bestAct = "ASSERT";
  let bestScore = scores.ASSERT;
  Object.keys(scores).forEach(act => {
    if (scores[act] > bestScore) {
      bestScore = scores[act];
      bestAct = act;
    }
  });

  return { act: bestAct, scores };
}

function renderActDecision(text, result) {
  const card = document.createElement("div");
  card.className = "act-card";

  const lines = [];
  lines.push("Input:");
  lines.push("  " + text);
  lines.push("");
  lines.push("Scores (toy heuristic):");
  Object.entries(result.scores).forEach(([k,v]) => {
    lines.push("  " + k + " = " + v.toFixed(2));
  });
  lines.push("");
  lines.push("Chosen act: " + result.act);
  lines.push("");
  lines.push("Why this matters:");
  lines.push("- Downstream CAPs and RS transitions depend on act type.");
  lines.push("- The same string can plausibly be ASK or COMMAND.");
  lines.push("- This toy makes that ambiguity explicit instead of hiding it.");

  card.textContent = lines.join("\n");
  actContainerEl.appendChild(card);
}

function runActClassification() {
  clearUI();
  const text = inputTextEl.value.trim();
  if (!text) {
    appendTrace("[ERROR] No input text.");
    return;
  }
  appendTrace("[INPUT] " + text);
  const result = classifyActWithScores(text);
  appendTrace("[ACT] " + result.act + " with scores " + JSON.stringify(result.scores));
  renderActDecision(text, result);
}

runButtonEl.addEventListener("click", runActClassification);

presetButtons.forEach(btn => {
  btn.addEventListener("click", () => {
    const key = btn.getAttribute("data-preset");
    inputTextEl.value = PRESETS[key] || "";
  });
});
</script>
</body>
</html>

HEG·03 — HEG — Emotion × Target Interaction

Demonstrates the EMOTION operator at the CAP→RS boundary. High-arousal negative inputs trigger different constraint weighting than neutral equivalents.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body{background:#050608;color:#e4f4e4;font-family:"IBM Plex Mono",Menlo,"Courier New",monospace;padding:20px;font-size:0.82rem;line-height:1.65;}
h1{color:#ffbf40;font-size:1.2rem;margin-bottom:0.3rem;letter-spacing:0.08em;}
h2{color:#ffd27f;font-size:1rem;margin-top:1.2rem;letter-spacing:0.06em;}
h3{color:#f1a85a;font-size:0.9rem;margin-top:1rem;}
label{color:#ffb86c;font-size:0.82rem;}
button{background:#111;color:#ffbf40;border:1px solid #444;padding:7px 12px;margin:4px 4px 8px 0;cursor:pointer;border-radius:3px;font-size:0.85rem;font-family:inherit;}
button:hover{background:#181008;border-color:#ffb86c;}
input,select,textarea{background:#0b0d10;color:#ffb86c;border:1px solid #3a2614;padding:4px 8px;font-family:inherit;font-size:0.8rem;border-radius:2px;}
pre,#output{background:#0b0d10;border:1px solid #222;padding:10px;max-height:420px;overflow:auto;font-size:0.78rem;color:#ffb86c;}
.small{font-size:0.82rem;color:#a8bfa8;}
.badge{font-size:0.78rem;color:#c0ffc0;margin-left:8px;border:1px solid #3a2614;padding:2px 6px;border-radius:2px;}
table{border-collapse:collapse;width:100%;margin-top:0.5rem;}
th{color:#ffbf40;border-bottom:1px solid #3a2614;padding:4px 8px;text-align:left;font-size:0.78rem;}
td{color:#e4f4e4;border-bottom:1px solid #1a1209;padding:4px 8px;font-size:0.78rem;}
</style>
<meta charset="UTF-8">
<title>HEG Toy 4 – Emotion × Target Interaction</title>

</head>
<body>
<div class="app-container">
  <!-- LEFT: Input -->
  <div class="pane left-pane">
    <div class="static-panel">
      <div class="static-header">HEG Toy 4 – Emotion × Target Interaction</div>
      <div class="static-label">
        Single operator under stress: EMOTION at the CAP → RS boundary, especially for CONSTRAINT.
      </div>
      <textarea id="inputText" placeholder="Example:
I’m a little worried this might be risky, but it’s probably fine."></textarea>
      <div class="section-title">Presets</div>
      <button class="preset-btn" data-preset="lowConstraint">Low-arousal CONSTRAINT</button>
      <button class="preset-btn" data-preset="highConstraint">High-arousal CONSTRAINT</button>
      <button class="preset-btn" data-preset="mixed">Mixed valence constraints</button>
      <div class="section-title">Run</div>
      <button id="runButton">Run Emotion × Target</button>
      <div class="small-note">
        Even with a stub RS, high-arousal constraints should land differently than low-arousal ones.
      </div>
    </div>
    <div class="dynamic-panel" id="traceArea"></div>
  </div>

  <!-- RIGHT: CAPs + RS -->
  <div class="pane right-pane">
    <div class="static-panel">
      <div class="static-header">CAPs & RS (Emotion-Sensitive)</div>
      <div class="static-label">
        We show how arousal modulates constraint priority in a toy RS.
      </div>
    </div>
    <div class="dynamic-panel" id="rightDynamic">
      <div class="section-title">CAPs</div>
      <div id="capsContainer"></div>
      <div class="section-title">Toy RS State</div>
      <div id="rsState" class="rs-state"></div>
    </div>
  </div>
</div>

<script>
const PRESETS = {
  lowConstraint: "I’m a little worried this might be risky, but it’s probably fine.",
  highConstraint: "This is way too risky, I’m really scared we’re going to blow this up.",
  mixed: "I’m excited about this plan, but I’m also genuinely worried that the safety checks are not enough."
};

const inputTextEl = document.getElementById("inputText");
const runButtonEl = document.getElementById("runButton");
const traceAreaEl = document.getElementById("traceArea");
const capsContainerEl = document.getElementById("capsContainer");
const rsStateEl = document.getElementById("rsState");
const presetButtons = document.querySelectorAll(".preset-btn");

function appendTrace(text) {
  const div = document.createElement("div");
  div.className = "trace-line";
  div.textContent = text;
  traceAreaEl.appendChild(div);
  traceAreaEl.scrollTop = traceAreaEl.scrollHeight;
}

function clearUI() {
  traceAreaEl.innerHTML = "";
  capsContainerEl.innerHTML = "";
  rsStateEl.textContent = "";
}

function segment(text) {
  return text
    .split(/(?<=[.?!])\s+/)
    .map(s => s.trim())
    .filter(s => s.length > 0);
}

function mapTargets(segment) {
  const lower = segment.toLowerCase();
  const targets = [];
  if (lower.includes("risky") || lower.includes("risk") || lower.includes("too risky")) {
    targets.push({ type:"CONSTRAINT", confidence:0.9 });
  }
  if (lower.includes("plan")) {
    targets.push({ type:"PLAN", confidence:0.9 });
  }
  if (!targets.length) {
    targets.push({ type:"UNKNOWN", confidence:0.5 });
  }
  return targets;
}

function extractEmotion(segment) {
  const lower = segment.toLowerCase();
  let valence = 0, arousal = 0;
  if (lower.includes("worried") || lower.includes("scared")) {
    valence -= 0.4; arousal += 0.5;
  }
  if (lower.includes("excited")) {
    valence += 0.4; arousal += 0.3;
  }
  if (lower.includes("too risky")) {
    valence -= 0.5; arousal += 0.4;
  }
  valence = Math.max(-1, Math.min(1, valence));
  arousal = Math.max(0, Math.min(1, arousal));
  return { valence, arousal };
}

function buildCAP(segment) {
  const targets = mapTargets(segment);
  const emotion = extractEmotion(segment);
  const cap = {
    payload: segment,
    targets,
    emotion,
    metadata: { id: Math.random().toString(16).slice(2,10) }
  };
  return cap;
}

function toyEmotionSensitiveRS(caps) {
  const state = {
    constraints: [],
    highPriorityConstraints: [],
    lowPriorityConstraints: [],
    notes: []
  };

  caps.forEach(cap => {
    cap.targets.forEach(t => {
      if (t.type === "CONSTRAINT") {
        state.constraints.push(cap.payload);
        if (cap.emotion.arousal >= 0.5) {
          state.highPriorityConstraints.push(cap.payload);
          state.notes.push("High-arousal constraint prioritized: " + cap.payload);
        } else {
          state.lowPriorityConstraints.push(cap.payload);
          state.notes.push("Low-arousal constraint registered but not prioritized: " + cap.payload);
        }
      }
    });
  });

  return state;
}

function renderCAP(cap, idx) {
  const card = document.createElement("div");
  card.className = "cap-card";
  const lines = [];
  lines.push("CAP #" + (idx+1));
  lines.push("Payload: " + cap.payload);
  lines.push("Targets: " + cap.targets.map(t => t.type).join(", "));
  lines.push("Emotion: valence=" + cap.emotion.valence.toFixed(2) +
             ", arousal=" + cap.emotion.arousal.toFixed(2));
  lines.push("");
  lines.push("Interpretation:");
  if (cap.targets.some(t => t.type === "CONSTRAINT")) {
    if (cap.emotion.arousal >= 0.5) {
      lines.push("- High-arousal CONSTRAINT → treated as urgent risk.");
    } else {
      lines.push("- Low-arousal CONSTRAINT → treated as background concern.");
    }
  } else {
    lines.push("- No explicit constraint target; emotion has no special effect here.");
  }
  card.textContent = lines.join("\n");
  capsContainerEl.appendChild(card);
}

function renderRSState(state) {
  const lines = [];
  lines.push("RS STATE (toy, emotion-sensitive)");
  lines.push("---------------------------------");
  lines.push("All constraints:");
  lines.push("  " + JSON.stringify(state.constraints));
  lines.push("");
  lines.push("High-priority constraints (high arousal):");
  lines.push("  " + JSON.stringify(state.highPriorityConstraints));
  lines.push("");
  lines.push("Low-priority constraints (low arousal):");
  lines.push("  " + JSON.stringify(state.lowPriorityConstraints));
  lines.push("");
  lines.push("Notes:");
  state.notes.forEach(n => lines.push("  - " + n));
  rsStateEl.textContent = lines.join("\n");
}

function runToy() {
  clearUI();
  const text = inputTextEl.value.trim();
  if (!text) {
    appendTrace("[ERROR] No input text.");
    return;
  }
  appendTrace("[INPUT] " + text);
  const segments = segment(text);
  appendTrace("[SEGMENT] " + segments.length + " segment(s).");
  const caps = segments.map(buildCAP);
  caps.forEach((cap, i) => {
    appendTrace("[CAP #" + (i+1) + "] " + JSON.stringify(cap));
    renderCAP(cap, i);
  });
  const rs = toyEmotionSensitiveRS(caps);
  renderRSState(rs);
}

runButtonEl.addEventListener("click", runToy);

presetButtons.forEach(btn => {
  btn.addEventListener("click", () => {
    const key = btn.getAttribute("data-preset");
    inputTextEl.value = PRESETS[key] || "";
  });
});
</script>
</body>
</html>

HEG·04 — HEG — Multimodal Fusion

Sends the same text through different synthetic audio and video contexts. The FUSION operator produces different CAPs depending on the combined modality signal. *Illustrative: audio/video inputs are text-described stand-ins for a browser demo, not real signal processing. Shows methodology, not measured multimodal performance.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body{background:#050608;color:#e4f4e4;font-family:"IBM Plex Mono",Menlo,"Courier New",monospace;padding:20px;font-size:0.82rem;line-height:1.65;}
h1{color:#ffbf40;font-size:1.2rem;margin-bottom:0.3rem;letter-spacing:0.08em;}
h2{color:#ffd27f;font-size:1rem;margin-top:1.2rem;letter-spacing:0.06em;}
h3{color:#f1a85a;font-size:0.9rem;margin-top:1rem;}
label{color:#ffb86c;font-size:0.82rem;}
button{background:#111;color:#ffbf40;border:1px solid #444;padding:7px 12px;margin:4px 4px 8px 0;cursor:pointer;border-radius:3px;font-size:0.85rem;font-family:inherit;}
button:hover{background:#181008;border-color:#ffb86c;}
input,select,textarea{background:#0b0d10;color:#ffb86c;border:1px solid #3a2614;padding:4px 8px;font-family:inherit;font-size:0.8rem;border-radius:2px;}
pre,#output{background:#0b0d10;border:1px solid #222;padding:10px;max-height:420px;overflow:auto;font-size:0.78rem;color:#ffb86c;}
.small{font-size:0.82rem;color:#a8bfa8;}
.badge{font-size:0.78rem;color:#c0ffc0;margin-left:8px;border:1px solid #3a2614;padding:2px 6px;border-radius:2px;}
table{border-collapse:collapse;width:100%;margin-top:0.5rem;}
th{color:#ffbf40;border-bottom:1px solid #3a2614;padding:4px 8px;text-align:left;font-size:0.78rem;}
td{color:#e4f4e4;border-bottom:1px solid #1a1209;padding:4px 8px;font-size:0.78rem;}
</style>
<meta charset="UTF-8">
<title>HEG Toy 5 – Multimodal Fusion</title>

</head>
<body>
<div class="app-container">
  <!-- LEFT: Scenario selection -->
  <div class="pane left-pane">
    <div class="static-panel">
      <div class="static-header">HEG Toy 5 – Multimodal Fusion</div>
      <div class="static-label">
        Single operator under stress: FUSION. Same semantic content, different modalities → different CAPs.
      </div>
      <div class="section-title">Scenarios</div>
      <button class="scenario-btn" data-scenario="calmText">Calm text, neutral audio/video</button>
      <button class="scenario-btn" data-scenario="angryAudio">Neutral text, angry audio</button>
      <button class="scenario-btn" data-scenario="confidentVideo">Neutral text, confident pointing video</button>
      <button class="scenario-btn" data-scenario="conflict">Text says fine, audio says furious</button>
      <div class="small-note">
        Point: CAPs are not just text. Modality changes act, targets, and emotion even with same words.
      </div>
    </div>
    <div class="dynamic-panel" id="traceArea"></div>
  </div>

  <!-- RIGHT: CAPs per modality + fused CAP -->
  <div class="pane right-pane">
    <div class="static-panel">
      <div class="static-header">Per-Modality CAPs + Fused CAP</div>
      <div class="static-label">
        We show text CAP, audio CAP, video CAP, then a fused CAP that RS would see.
      </div>
    </div>
    <div class="dynamic-panel" id="rightDynamic">
      <div class="section-title">Text CAP</div>
      <div id="textCap" class="cap-card"></div>
      <div class="section-title">Audio CAP</div>
      <div id="audioCap" class="cap-card"></div>
      <div class="section-title">Video CAP</div>
      <div id="videoCap" class="cap-card"></div>
      <div class="section-title">Fused CAP (Toy)</div>
      <div id="fusedCap" class="cap-card"></div>
    </div>
  </div>
</div>

<script>
const traceAreaEl = document.getElementById("traceArea");
const textCapEl = document.getElementById("textCap");
const audioCapEl = document.getElementById("audioCap");
const videoCapEl = document.getElementById("videoCap");
const fusedCapEl = document.getElementById("fusedCap");
const scenarioButtons = document.querySelectorAll(".scenario-btn");

function appendTrace(text) {
  const div = document.createElement("div");
  div.className = "trace-line";
  div.textContent = text;
  traceAreaEl.appendChild(div);
  traceAreaEl.scrollTop = traceAreaEl.scrollHeight;
}

function clearUI() {
  traceAreaEl.innerHTML = "";
  textCapEl.textContent = "";
  audioCapEl.textContent = "";
  videoCapEl.textContent = "";
  fusedCapEl.textContent = "";
}

function buildTextCAP(text) {
  const lower = text.toLowerCase();
  const targets = [];
  if (lower.includes("plan")) targets.push("PLAN");
  if (lower.includes("risk") || lower.includes("risky")) targets.push("CONSTRAINT");
  if (!targets.length) targets.push("UNKNOWN");
  return {
    modality: "text",
    act: "ASSERT",
    targets,
    emotion: { valence: 0.0, arousal: 0.1 },
    payload: text
  };
}

function buildAudioCAP(description) {
  const lower = description.toLowerCase();
  let valence = 0, arousal = 0;
  let act = "ASSERT";
  if (lower.includes("angry") || lower.includes("furious")) {
    valence -= 0.6; arousal += 0.7; act = "COMMAND";
  }
  if (lower.includes("calm")) {
    valence += 0.1; arousal += 0.1;
  }
  return {
    modality: "audio",
    act,
    targets: ["MODE"],
    emotion: { valence, arousal },
    payload: description
  };
}

function buildVideoCAP(description) {
  const lower = description.toLowerCase();
  let act = "ASSERT";
  const targets = [];
  let arousal = 0.1;
  if (lower.includes("pointing")) {
    act = "COMMAND";
    targets.push("PLAN");
    arousal += 0.3;
  }
  if (!targets.length) targets.push("UNKNOWN");
  return {
    modality: "video",
    act,
    targets,
    emotion: { valence: 0.0, arousal },
    payload: description
  };
}

function fuseCAPs(textCap, audioCap, videoCap) {
  // Toy fusion: majority vote on act, union of targets, max arousal, average valence
  const acts = [textCap.act, audioCap.act, videoCap.act];
  const actCounts = {};
  acts.forEach(a => { actCounts[a] = (actCounts[a] || 0) + 1; });
  let fusedAct = acts[0];
  let bestCount = 0;
  Object.entries(actCounts).forEach(([a,c]) => {
    if (c > bestCount) { bestCount = c; fusedAct = a; }
  });

  const targetSet = new Set();
  textCap.targets.forEach(t => targetSet.add(t));
  audioCap.targets.forEach(t => targetSet.add(t));
  videoCap.targets.forEach(t => targetSet.add(t));

  const fusedValence = (textCap.emotion.valence + audioCap.emotion.valence + videoCap.emotion.valence) / 3;
  const fusedArousal = Math.max(textCap.emotion.arousal, audioCap.emotion.arousal, videoCap.emotion.arousal);

  return {
    modality: "fused",
    act: fusedAct,
    targets: Array.from(targetSet),
    emotion: { valence: fusedValence, arousal: fusedArousal },
    payload: {
      text: textCap.payload,
      audio: audioCap.payload,
      video: videoCap.payload
    }
  };
}

function renderCap(el, cap, label) {
  if (!cap) { el.textContent = "(none)"; return; }
  const lines = [];
  lines.push(label + " CAP");
  lines.push("Modality: " + cap.modality);
  lines.push("Act: " + cap.act);
  lines.push("Targets: " + (Array.isArray(cap.targets) ? cap.targets.join(", ") : JSON.stringify(cap.targets)));
  lines.push("Emotion: valence=" + cap.emotion.valence.toFixed(2) +
             ", arousal=" + cap.emotion.arousal.toFixed(2));
  lines.push("");
  lines.push("Payload:");
  lines.push(typeof cap.payload === "string" ? cap.payload : JSON.stringify(cap.payload, null, 2));
  el.textContent = lines.join("\n");
}

function runScenario(name) {
  clearUI();
  let text, audioDesc, videoDesc;

  if (name === "calmText") {
    text = "The plan seems fine; let’s just walk through the steps carefully.";
    audioDesc = "[AUDIO] Calm, steady tone, medium volume.";
    videoDesc = "[VIDEO] Neutral posture, no pointing, relaxed.";
  } else if (name === "angryAudio") {
    text = "The plan seems fine; let’s just walk through the steps carefully.";
    audioDesc = "[AUDIO] Angry, raised voice, sharp emphasis.";
    videoDesc = "[VIDEO] Neutral posture, no pointing, relaxed.";
  } else if (name === "confidentVideo") {
    text = "The plan seems fine; let’s just walk through the steps carefully.";
    audioDesc = "[AUDIO] Calm, steady tone, medium volume.";
    videoDesc = "[VIDEO] User pointing at the screen, leaning forward, confident.";
  } else if (name === "conflict") {
    text = "It’s fine, really, I’m not upset at all.";
    audioDesc = "[AUDIO] Furious, clipped speech, high arousal.";
    videoDesc = "[VIDEO] Tense posture, slight shaking, no explicit pointing.";
  } else {
    return;
  }

  appendTrace("[SCENARIO] " + name);
  appendTrace("Text: " + text);
  appendTrace("Audio: " + audioDesc);
  appendTrace("Video: " + videoDesc);

  const textCap = buildTextCAP(text);
  const audioCap = buildAudioCAP(audioDesc);
  const videoCap = buildVideoCAP(videoDesc);
  const fusedCap = fuseCAPs(textCap, audioCap, videoCap);

  appendTrace("[TEXT CAP] " + JSON.stringify(textCap));
  appendTrace("[AUDIO CAP] " + JSON.stringify(audioCap));
  appendTrace("[VIDEO CAP] " + JSON.stringify(videoCap));
  appendTrace("[FUSED CAP] " + JSON.stringify(fusedCap));

  renderCap(textCapEl, textCap, "Text");
  renderCap(audioCapEl, audioCap, "Audio");
  renderCap(videoCapEl, videoCap, "Video");
  renderCap(fusedCapEl, fusedCap, "Fused");
}

scenarioButtons.forEach(btn => {
  btn.addEventListener("click", () => {
    const scenario = btn.getAttribute("data-scenario");
    runScenario(scenario);
  });
});
</script>
</body>
</html>

RPU·01 — RPU — Packet Storm Harness

Flood of hostile packets. Transformer state leaks; RPU-Classic isolates; RPU-Quantum sheds excess via energy-guided shedding.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>RPU · Packet Storm (Verified Mechanism)</title>
<style>
  body { font-family:"IBM Plex Mono","SF Mono",Menlo,monospace; background:#050302; color:#ffb86c; margin:0; padding:16px; }
  h1 { font-size:1rem; text-transform:uppercase; letter-spacing:0.08em; margin:0 0 4px; }
  .sub { font-size:0.72rem; color:#c28a4a; margin-bottom:12px; line-height:1.5; }
  .grid { display:flex; gap:12px; flex-wrap:wrap; }
  .panel { flex:1 1 260px; min-width:260px; background:radial-gradient(circle at top,#1b1008 0,#0a0503 70%); border:1px solid #3a2614; border-radius:8px; padding:10px; box-shadow:0 0 6px rgba(255,184,108,0.18) inset; }
  .panel h2 { font-size:0.78rem; text-transform:uppercase; letter-spacing:0.08em; margin:0 0 6px; color:#f1a85a; }
  canvas { width:100%; height:110px; background:#050302; border:1px solid #3a2614; border-radius:4px; display:block; margin-bottom:6px; }
  .stat { font-size:0.72rem; margin:2px 0; }
  .stat b { color:#ffb86c; }
  .log { font-size:0.68rem; max-height:140px; overflow:auto; background:#050302; border:1px solid #3a2614; border-radius:4px; padding:6px; white-space:pre-wrap; }
  button { background:#3a2614; color:#ffb86c; border:1px solid #3a2614; border-radius:4px; padding:0.4rem 0.8rem; font-family:inherit; font-size:0.75rem; text-transform:uppercase; letter-spacing:0.08em; cursor:pointer; margin:0 6px 10px 0; }
  button:hover { background:#4a311b; }
  .note { font-size:0.68rem; color:#c28a4a; margin-top:10px; line-height:1.5; }
</style>
</head>
<body>

<h1>RPU · Packet Storm</h1>
<div class="sub">
  Identical packet stream hits all three panels — same forcing, same order, no special-casing.
  Naive: raw accumulation, no defense. RPU-Classic: hard clamp with real decay — bounded, but
  can saturate and pin at the ceiling under sustained load. RPU-Quantum: the same clamp,
  plus the verified invariant + collapse mechanism, actively shedding load a hard clamp
  alone cannot avoid.
</div>

<button id="runBtn">Run All Three</button>
<button id="resetBtn">Reset</button>

<div class="grid">
  <div class="panel">
    <h2>Naive — No Defense</h2>
    <canvas id="canT" width="300" height="110"></canvas>
    <div class="stat">Final load: <b id="finalT">—</b></div>
    <div class="stat">Peak load: <b id="peakT">—</b></div>
    <div class="log" id="logT"></div>
  </div>

  <div class="panel">
    <h2>RPU-Classic — Hard Clamp</h2>
    <canvas id="canC" width="300" height="110"></canvas>
    <div class="stat">Final load: <b id="finalC">—</b></div>
    <div class="stat">Times pinned at ceiling: <b id="pinsC">—</b></div>
    <div class="log" id="logC"></div>
  </div>

  <div class="panel">
    <h2>RPU-Quantum — Clamp + Invariant + Collapse</h2>
    <canvas id="canQ" width="300" height="110"></canvas>
    <div class="stat">Final load: <b id="finalQ">—</b></div>
    <div class="stat">Times pinned at ceiling: <b id="pinsQ">—</b></div>
    <div class="log" id="logQ"></div>
  </div>
</div>

<div class="note">
  Verification note: this uses the same clamp / invariant / collapse mechanism verified earlier
  as a three-way separation (~0.04 vs ~5 vs ~665 magnitude), now driven by real packet-derived
  forcing instead of synthetic perturbation. All three panels receive byte-identical packet
  forcing — Classic and Quantum are not given different inputs, only different response logic.
</div>

<script>
const CAP = 100, DECAY = 6;

function generatePackets(seed) {
  const stream = [];
  for (let i = 0; i < 40; i++) {
    const roll = (i + seed) % 7;
    if (roll === 0) stream.push({ kind: "volumetric", force: 40 });
    else if (roll === 3) stream.push({ kind: "semantic", force: 15 });
    else stream.push({ kind: "normal", force: 2 });
  }
  return stream;
}

function invariantOk(prevL, candL) { return Math.abs(candL) <= Math.abs(prevL) + 8; }

function runNaive(stream) {
  let L = 0; const series = [L];
  for (const p of stream) { L += p.force; series.push(L); }
  return series;
}
function runClassic(stream) {
  let L = 0; const series = [L]; let pins = 0;
  for (const p of stream) {
    L = L + p.force - DECAY;
    L = Math.max(0, Math.min(CAP, L));
    if (L === CAP) pins++;
    series.push(L);
  }
  return { series, pins };
}
function runQuantum(stream) {
  let L = 0; const series = [L]; let pins = 0;
  for (const p of stream) {
    const forced = L + p.force - DECAY;
    const clamped = Math.max(0, Math.min(CAP, forced));
    const candidates = [clamped, clamped - 10, clamped - 20, clamped - 5];
    let chosen = clamped;
    for (const c of candidates) {
      if (c >= 0 && invariantOk(L, c)) { chosen = c; break; }
    }
    L = chosen;
    if (L === CAP) pins++;
    series.push(L);
  }
  return { series, pins };
}

function log(id, msg) {
  const el = document.getElementById(id);
  el.textContent += msg + "\n";
  el.scrollTop = el.scrollHeight;
}
function plot(canvasId, series, color, cap) {
  const c = document.getElementById(canvasId);
  const ctx = c.getContext("2d");
  ctx.clearRect(0,0,c.width,c.height);
  ctx.strokeStyle = "#3a2614"; ctx.lineWidth = 1;
  const capY = c.height - (cap / Math.max(cap, Math.max(...series))) * (c.height - 10) - 5;
  ctx.beginPath(); ctx.moveTo(0, capY); ctx.lineTo(c.width, capY); ctx.stroke();
  const max = Math.max(...series, cap);
  ctx.strokeStyle = color; ctx.lineWidth = 1.5; ctx.beginPath();
  series.forEach((v, i) => {
    const x = (i / (series.length - 1)) * c.width;
    const y = c.height - (v / max) * (c.height - 10) - 5;
    i === 0 ? ctx.moveTo(x,y) : ctx.lineTo(x,y);
  });
  ctx.stroke();
}

document.getElementById('runBtn').onclick = () => {
  ['T','C','Q'].forEach(p => document.getElementById('log'+p).textContent = '');
  const stream = generatePackets(0);

  const naive = runNaive(stream);
  document.getElementById('finalT').textContent = naive[naive.length-1];
  document.getElementById('peakT').textContent = Math.max(...naive);
  plot('canT', naive, '#c28a4a', CAP);
  log('logT', `Ran ${stream.length} packets, no defense.\nLoad grew unbounded to ${naive[naive.length-1]}.`);

  const classic = runClassic(stream);
  document.getElementById('finalC').textContent = classic.series[classic.series.length-1];
  document.getElementById('pinsC').textContent = classic.pins;
  plot('canC', classic.series, '#f1a85a', CAP);
  log('logC', `Ran ${stream.length} packets, hard clamp only.\nBounded to [0,${CAP}], but pinned at the ceiling ${classic.pins} times under sustained load.`);

  const quantum = runQuantum(stream);
  document.getElementById('finalQ').textContent = quantum.series[quantum.series.length-1];
  document.getElementById('pinsQ').textContent = quantum.pins;
  plot('canQ', quantum.series, '#ffb86c', CAP);
  log('logQ', `Ran ${stream.length} packets, clamp + invariant + collapse.\nSame packet stream as Classic. Pinned at ceiling ${quantum.pins} times — actively shed load instead of saturating.`);
};

document.getElementById('resetBtn').onclick = () => {
  ['T','C','Q'].forEach(p => {
    document.getElementById('log'+p).textContent = '';
    document.getElementById('final'+p) && (document.getElementById('final'+p).textContent = '—');
  });
  document.getElementById('peakT').textContent = '—';
  document.getElementById('pinsC').textContent = '—';
  document.getElementById('pinsQ').textContent = '—';
  ['canT','canC','canQ'].forEach(id => {
    const c = document.getElementById(id);
    c.getContext('2d').clearRect(0,0,c.width,c.height);
  });
};
</script>
</body>
</html>

RPU·02 — RPU — Constraint Solver Harness

A 4×4 grid constraint puzzle solved across three engines. Classic applies contraction; Quantum uses perturbation; Transformer iterates without convergence guarantees.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html>
<head>
  <title>RPU Constraint Solver Harness</title>
  <style>
    body { font-family: Arial; background:#111; color:#eee; margin:20px; }
    h1 { color:#6cf; }
    p.subtitle { color:#aaa; margin-top:0; font-size:0.9em; }
    .container { display:flex; gap:20px; margin-top:20px; }
    .panel { background:#222; padding:15px; border-radius:8px; width:32%; }
    button { padding:8px 12px; margin:5px; border:none; border-radius:4px; cursor:pointer; }
    .run { background:#4caf50; color:white; }
    .reset { background:#f44336; color:white; }
    .output { background:#000; color:#0f0; padding:10px; height:200px; overflow:auto; font-family:monospace; }
    .canvas-box { background:#000; border:1px solid #333; margin-top:10px; }
    .engine-sub { color:#aaa; font-size:0.8em; margin-top:-6px; margin-bottom:8px; }
    .header { display:flex; justify-content:space-between; align-items:center; }
  </style>
</head>
<body>
<h1>RPU Constraint Solver Harness</h1>
<p class="subtitle">
Tiny constraint puzzle — 4×4 grid must satisfy simple rules. Transformer flails. Classic converges. Quantum escapes traps.
</p>

<div class="header">
  <div>
    <button class="run" onclick="runAll()">Run All</button>
    <button class="reset" onclick="resetAll()">Reset All</button>
  </div>
</div>

<div class="container">
  <div class="panel">
    <h2>Transformer</h2>
    <div class="engine-sub">Shared Context (Fragile)</div>
    <button class="run" onclick="runTransformer()">Run</button>
    <button class="reset" onclick="resetPanel('out1','can1')">Reset</button>
    <canvas id="can1" width="300" height="120" class="canvas-box"></canvas>
    <div id="out1" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Classic</h2>
    <div class="engine-sub">Hard Separation (Stable)</div>
    <button class="run" onclick="runClassic()">Run</button>
    <button class="reset" onclick="resetPanel('out2','can2')">Reset</button>
    <canvas id="can2" width="300" height="120" class="canvas-box"></canvas>
    <div id="out2" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Quantum</h2>
    <div class="engine-sub">Energy-Regulated (Adaptive)</div>
    <button class="run" onclick="runQuantum()">Run</button>
    <button class="reset" onclick="resetPanel('out3','can3')">Reset</button>
    <canvas id="can3" width="300" height="120" class="canvas-box"></canvas>
    <div id="out3" class="output"></div>
  </div>
</div>

<script>
function log(id,msg){const el=document.getElementById(id);el.innerHTML+=msg+"<br>";el.scrollTop=el.scrollHeight;}
function resetPanel(outId,canId){
  document.getElementById(outId).innerHTML="";
  const ctx=document.getElementById(canId).getContext("2d");
  ctx.fillStyle="#000";ctx.fillRect(0,0,300,120);
}
function resetAll(){resetPanel('out1','can1');resetPanel('out2','can2');resetPanel('out3','can3');}
function runAll(){runTransformer();runClassic();runQuantum();}

const SIZE=4;
function drawGrid(canvasId, grid){
  const ctx=document.getElementById(canvasId).getContext("2d");
  ctx.fillStyle="#000";ctx.fillRect(0,0,300,120);
  const cw=300/SIZE, ch=120/SIZE;
  for(let i=0;i<SIZE;i++){
    for(let j=0;j<SIZE;j++){
      const v=grid[i][j];
      ctx.fillStyle=v===0?"#333":v===1?"#0f0":"#f00";
      ctx.fillRect(j*cw, i*ch, cw-2, ch-2);
    }
  }
}

// Simple constraint: each row must sum to 2, each col must sum to 2
function violations(grid){
  let v=0;
  for(let i=0;i<SIZE;i++){
    const rs=grid[i].reduce((a,b)=>a+b,0);
    v+=Math.abs(rs-2);
  }
  for(let j=0;j<SIZE;j++){
    let cs=0;for(let i=0;i<SIZE;i++)cs+=grid[i][j];
    v+=Math.abs(cs-2);
  }
  return v;
}

// Transformer: random flips, no guided descent
function runTransformer(){
  resetPanel('out1','can1');
  log('out1',"Starting Transformer Constraint Solver...");
  let grid = Array.from({length:SIZE},()=>Array.from({length:SIZE},()=>Math.random()<0.5?0:1));
  drawGrid("can1",grid);
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      for(let k=0;k<3;k++){
        const i=Math.floor(Math.random()*SIZE);
        const j=Math.floor(Math.random()*SIZE);
        grid[i][j]=Math.random()<0.5?0:1;
      }
      const v=violations(grid);
      drawGrid("can1",grid);
      log('out1',`[t=${t}] violations=${v}`);
    },t*80);
  }
}

// Classic: greedy local improvement
function runClassic(){
  resetPanel('out2','can2');
  log('out2',"Starting RPU-Classic Constraint Solver...");
  let grid = Array.from({length:SIZE},()=>Array.from({length:SIZE},()=>Math.random()<0.5?0:1));
  drawGrid("can2",grid);
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      for(let i=0;i<SIZE;i++){
        for(let j=0;j<SIZE;j++){
          const current=grid[i][j];
          grid[i][j]=1-current;
          const vNew=violations(grid);
          grid[i][j]=current;
          const vOld=violations(grid);
          if(vNew<vOld) grid[i][j]=1-current;
        }
      }
      const v=violations(grid);
      drawGrid("can2",grid);
      log('out2',`[t=${t}] violations=${v}`);
    },t*80);
  }
}

// Quantum: occasional random jumps to escape local minima
function runQuantum(){
  resetPanel('out3','can3');
  log('out3',"Starting RPU-Quantum Constraint Solver...");
  let grid = Array.from({length:SIZE},()=>Array.from({length:SIZE},()=>Math.random()<0.5?0:1));
  drawGrid("can3",grid);
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      for(let i=0;i<SIZE;i++){
        for(let j=0;j<SIZE;j++){
          const current=grid[i][j];
          grid[i][j]=1-current;
          let vNew=violations(grid);
          grid[i][j]=current;
          let vOld=violations(grid);
          if(vNew<vOld || Math.random()<0.1) grid[i][j]=1-current;
        }
      }
      const v=violations(grid);
      drawGrid("can3",grid);
      log('out3',`[t=${t}] violations=${v}`);
    },t*80);
  }
}
</script>
</body>
</html>

RPU·03 — RPU — Constraint-to-Energy Compiler

User-defined constraints compiled into E(x) energy function. Both RPU variants minimize from random starting states.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html>
<head>
  <title>RPU Constraint-to-Energy Compiler Harness</title>
  <style>
    body { font-family: Arial; background:#111; color:#eee; margin:20px; }
    h1 { color:#6cf; }
    p.subtitle { color:#aaa; margin-top:0; font-size:0.9em; }
    .container { display:flex; gap:20px; margin-top:20px; }
    .panel { background:#222; padding:15px; border-radius:8px; width:32%; }
    button { padding:8px 12px; margin:5px; border:none; border-radius:4px; cursor:pointer; }
    .run { background:#4caf50; color:white; }
    .reset { background:#f44336; color:white; }
    .output { background:#000; color:#0f0; padding:10px; height:200px; overflow:auto; font-family:monospace; }
    .canvas-box { background:#000; border:1px solid #333; margin-top:10px; height:120px; }
    .engine-sub { color:#aaa; font-size:0.8em; margin-top:-6px; margin-bottom:8px; }
    .header { display:flex; justify-content:space-between; align-items:center; }
    .controls { margin-top:10px; font-size:0.85em; color:#ccc; }
    .controls input { background:#111; color:#eee; border:1px solid #444; padding:4px; margin-right:4px; }
  </style>
</head>
<body>
<h1>RPU Constraint-to-Energy Compiler Harness</h1>
<p class="subtitle">
User constraints → energy function E(x) → engines try to satisfy. Transformer struggles. Classic and Quantum descend.
</p>

<div class="header">
  <button class="run" onclick="runAll()">Run All</button>
  <button class="reset" onclick="resetAll()">Reset All</button>
</div>

<div class="controls">
  Target sum: <input id="targetSum" type="number" value="10">
  Penalty weight: <input id="penaltyW" type="number" value="1.0" step="0.1">
  <button class="run" onclick="compileConstraints()">Compile Constraints</button>
  <span id="compiledInfo"></span>
</div>

<div class="container">
  <div class="panel">
    <h2>Transformer</h2>
    <div class="engine-sub">Shared Context (Fragile)</div>
    <button class="run" onclick="runTransformer()">Run</button>
    <button class="reset" onclick="resetPanel('out1','can1')">Reset</button>
    <canvas id="can1" width="300" height="120" class="canvas-box"></canvas>
    <div id="out1" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Classic</h2>
    <div class="engine-sub">Hard Separation (Stable)</div>
    <button class="run" onclick="runClassic()">Run</button>
    <button class="reset" onclick="resetPanel('out2','can2')">Reset</button>
    <canvas id="can2" width="300" height="120" class="canvas-box"></canvas>
    <div id="out2" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Quantum</h2>
    <div class="engine-sub">Energy-Regulated (Adaptive)</div>
    <button class="run" onclick="runQuantum()">Run</button>
    <button class="reset" onclick="resetPanel('out3','can3')">Reset</button>
    <canvas id="can3" width="300" height="120" class="canvas-box"></canvas>
    <div id="out3" class="output"></div>
  </div>
</div>

<script>
function log(id,msg){const el=document.getElementById(id);el.innerHTML+=msg+"<br>";el.scrollTop=el.scrollHeight;}
function resetPanel(out,can){document.getElementById(out).innerHTML="";const c=document.getElementById(can).getContext("2d");c.fillStyle="#000";c.fillRect(0,0,300,120);}
function resetAll(){resetPanel('out1','can1');resetPanel('out2','can2');resetPanel('out3','can3');}
function runAll(){runTransformer();runClassic();runQuantum();}

let target=10, weight=1.0;
function compileConstraints(){
  target=parseFloat(document.getElementById("targetSum").value)||10;
  weight=parseFloat(document.getElementById("penaltyW").value)||1.0;
  document.getElementById("compiledInfo").textContent=`E(x) = weight * (sum(x) - ${target})^2`;
}

function energy(vec){
  const s=vec.reduce((a,b)=>a+b,0);
  return weight*(s-target)*(s-target);
}

function drawVec(canvasId, vec){
  const ctx=document.getElementById(canvasId).getContext("2d");
  ctx.fillStyle="#000";ctx.fillRect(0,0,300,120);
  const w=300/vec.length;
  vec.forEach((v,i)=>{
    const h=v*5;
    ctx.fillStyle="#0f0";
    ctx.fillRect(i*w+2, 100-h, w-4, h);
  });
}

// Transformer: random updates
function runTransformer(){
  resetPanel('out1','can1');
  log('out1',"Running Transformer on compiled E(x)...");
  let vec=[1,2,3,4];
  drawVec("can1",vec);
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      const i=Math.floor(Math.random()*vec.length);
      vec[i]+= (Math.random()-0.5)*4;
      const E=energy(vec);
      drawVec("can1",vec);
      log('out1',`[t=${t}] sum=${vec.reduce((a,b)=>a+b,0).toFixed(2)} E=${E.toFixed(2)}`);
    },t*80);
  }
}

// Classic: gradient-like descent on sum
function runClassic(){
  resetPanel('out2','can2');
  log('out2',"Running RPU-Classic on compiled E(x)...");
  let vec=[1,2,3,4];
  drawVec("can2",vec);
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      const s=vec.reduce((a,b)=>a+b,0);
      const diff=s-target;
      vec=vec.map(v=>v - 0.1*diff/vec.length);
      const E=energy(vec);
      drawVec("can2",vec);
      log('out2',`[t=${t}] sum=${s.toFixed(2)} E=${E.toFixed(2)}`);
    },t*80);
  }
}

// Quantum: descent + small noise
function runQuantum(){
  resetPanel('out3','can3');
  log('out3',"Running RPU-Quantum on compiled E(x)...");
  let vec=[1,2,3,4];
  drawVec("can3",vec);
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      const s=vec.reduce((a,b)=>a+b,0);
      const diff=s-target;
      vec=vec.map(v=>v - 0.09*diff/vec.length + (Math.random()-0.5)*0.1);
      const E=energy(vec);
      drawVec("can3",vec);
      log('out3',`[t=${t}] sum=${s.toFixed(2)} E=${E.toFixed(2)}`);
    },t*80);
  }
}
compileConstraints();
</script>
</body>
</html>

RPU·04 — RPU — Energy Landscape Explorer

A single reasoning state traverses a visualized energy surface. Classic follows gradient descent; Quantum adds noise to escape local minima.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html>
<head>
  <title>RPU Energy Landscape Explorer</title>
  <style>
    body { font-family: Arial; background:#111; color:#eee; margin:20px; }
    h1 { color:#6cf; }
    p.subtitle { color:#aaa; margin-top:0; font-size:0.9em; }
    .container { display:flex; gap:20px; margin-top:20px; }
    .panel { background:#222; padding:15px; border-radius:8px; width:32%; }
    button { padding:8px 12px; margin:5px; border:none; border-radius:4px; cursor:pointer; }
    .run { background:#4caf50; color:white; }
    .reset { background:#f44336; color:white; }
    .output { background:#000; color:#0f0; padding:10px; height:200px; overflow:auto; font-family:monospace; }
    .canvas-box { background:#000; border:1px solid #333; margin-top:10px; }
    .engine-sub { color:#aaa; font-size:0.8em; margin-top:-6px; margin-bottom:8px; }
    .header { display:flex; justify-content:space-between; align-items:center; }
  </style>
</head>
<body>
<h1>RPU Energy Landscape Explorer</h1>
<p class="subtitle">
Single state rolling across an energy surface. Transformer jumps. Classic rolls down. Quantum samples and settles.
</p>

<div class="header">
  <button class="run" onclick="runAll()">Run All</button>
  <button class="reset" onclick="resetAll()">Reset All</button>
</div>

<div class="container">
  <div class="panel">
    <h2>Transformer</h2>
    <div class="engine-sub">Shared Context (Fragile)</div>
    <button class="run" onclick="runTransformer()">Run</button>
    <button class="reset" onclick="resetPanel('out1','can1')">Reset</button>
    <canvas id="can1" width="300" height="120" class="canvas-box"></canvas>
    <div id="out1" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Classic</h2>
    <div class="engine-sub">Hard Separation (Stable)</div>
    <button class="run" onclick="runClassic()">Run</button>
    <button class="reset" onclick="resetPanel('out2','can2')">Reset</button>
    <canvas id="can2" width="300" height="120" class="canvas-box"></canvas>
    <div id="out2" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Quantum</h2>
    <div class="engine-sub">Energy-Regulated (Adaptive)</div>
    <button class="run" onclick="runQuantum()">Run</button>
    <button class="reset" onclick="resetPanel('out3','can3')">Reset</button>
    <canvas id="can3" width="300" height="120" class="canvas-box"></canvas>
    <div id="out3" class="output"></div>
  </div>
</div>

<script>
function log(id,msg){const el=document.getElementById(id);el.innerHTML+=msg+"<br>";el.scrollTop=el.scrollHeight;}
function resetPanel(outId,canId){
  document.getElementById(outId).innerHTML="";
  const ctx=document.getElementById(canId).getContext("2d");
  ctx.fillStyle="#000";ctx.fillRect(0,0,300,120);
}
function resetAll(){resetPanel('out1','can1');resetPanel('out2','can2');resetPanel('out3','can3');}
function runAll(){runTransformer();runClassic();runQuantum();}

function energy(x){return 0.5*x*x + 0.3*Math.cos(3*x);}
function grad(x){return x - 0.9*Math.sin(3*x);}

function drawState(canvasId,x){
  const ctx=document.getElementById(canvasId).getContext("2d");
  ctx.fillStyle="#000";ctx.fillRect(0,0,300,120);
  ctx.strokeStyle="#333";
  ctx.beginPath();
  for(let i=0;i<300;i++){
    const xx=(i-150)/30;
    const yy=energy(xx);
    const y=100-yy*10;
    if(i===0) ctx.moveTo(i,y); else ctx.lineTo(i,y);
  }
  ctx.stroke();
  const px=150 + x*30;
  const py=100 - energy(x)*10;
  ctx.fillStyle="#6cf";
  ctx.beginPath();
  ctx.arc(px,py,5,0,Math.PI*2);
  ctx.fill();
}

// Transformer: noisy jumps
function runTransformer(){
  resetPanel('out1','can1');
  log('out1',"Starting Transformer energy walk...");
  let x=(Math.random()-0.5)*4;
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      x = x + (Math.random()-0.5)*1.5;
      drawState("can1",x);
      log('out1',`[t=${t}] x=${x.toFixed(3)} E=${energy(x).toFixed(3)}`);
    },t*80);
  }
}

// Classic: gradient descent
function runClassic(){
  resetPanel('out2','can2');
  log('out2',"Starting RPU-Classic descent...");
  let x=(Math.random()-0.5)*4;
  const tau=0.08;
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      x = x - tau*grad(x);
      drawState("can2",x);
      log('out2',`[t=${t}] x=${x.toFixed(3)} E=${energy(x).toFixed(3)}`);
    },t*80);
  }
}

// Quantum: descent + exploration
function runQuantum(){
  resetPanel('out3','can3');
  log('out3',"Starting RPU-Quantum descent...");
  let x=(Math.random()-0.5)*4;
  const tau=0.06;
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      const explore=(Math.random()-0.5)*0.4*(t<20?1:0.2);
      x = x - tau*grad(x) + explore;
      drawState("can3",x);
      log('out3',`[t=${t}] x=${x.toFixed(3)} E=${energy(x).toFixed(3)}`);
    },t*80);
  }
}
</script>
</body>
</html>

RPU·05 — RPU — Lattice Convergence Harness

8×8 multi-cell grid descends energy simultaneously. Color shows cells from high-energy (red) to stable (green).

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html>
<head>
  <title>RPU Lattice Convergence Harness</title>
  <style>
    body { font-family: Arial; background:#111; color:#eee; margin:20px; }
    h1 { color:#6cf; }
    p.subtitle { color:#aaa; margin-top:0; font-size:0.9em; }
    .container { display:flex; gap:20px; margin-top:20px; }
    .panel { background:#222; padding:15px; border-radius:8px; width:32%; }
    button { padding:8px 12px; margin:5px; border:none; border-radius:4px; cursor:pointer; }
    .run { background:#4caf50; color:white; }
    .reset { background:#f44336; color:white; }
    .output { background:#000; color:#0f0; padding:10px; height:200px; overflow:auto; font-family:monospace; }
    .canvas-box { background:#000; border:1px solid #333; margin-top:10px; }
    .engine-sub { color:#aaa; font-size:0.8em; margin-top:-6px; margin-bottom:8px; }
    .header { display:flex; justify-content:space-between; align-items:center; }
  </style>
</head>
<body>
<h1>RPU Lattice Convergence Harness</h1>
<p class="subtitle">
Multi-Cell Energy Descent — small grid of cells updating together. Transformer thrashes. Classic contracts. Quantum explores then settles.
</p>

<div class="header">
  <div>
    <button class="run" onclick="runAll()">Run All</button>
    <button class="reset" onclick="resetAll()">Reset All</button>
  </div>
</div>

<div class="container">
  <div class="panel">
    <h2>Transformer</h2>
    <div class="engine-sub">Shared Context (Fragile)</div>
    <button class="run" onclick="runTransformer()">Run</button>
    <button class="reset" onclick="resetPanel('out1','can1')">Reset</button>
    <canvas id="can1" width="300" height="120" class="canvas-box"></canvas>
    <div id="out1" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Classic</h2>
    <div class="engine-sub">Hard Separation (Stable)</div>
    <button class="run" onclick="runClassic()">Run</button>
    <button class="reset" onclick="resetPanel('out2','can2')">Reset</button>
    <canvas id="can2" width="300" height="120" class="canvas-box"></canvas>
    <div id="out2" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Quantum</h2>
    <div class="engine-sub">Energy-Regulated (Adaptive)</div>
    <button class="run" onclick="runQuantum()">Run</button>
    <button class="reset" onclick="resetPanel('out3','can3')">Reset</button>
    <canvas id="can3" width="300" height="120" class="canvas-box"></canvas>
    <div id="out3" class="output"></div>
  </div>
</div>

<script>
function log(id,msg){const el=document.getElementById(id);el.innerHTML+=msg+"<br>";el.scrollTop=el.scrollHeight;}
function resetPanel(outId,canId){
  document.getElementById(outId).innerHTML="";
  const ctx=document.getElementById(canId).getContext("2d");
  ctx.fillStyle="#000";ctx.fillRect(0,0,300,120);
}
function resetAll(){resetPanel('out1','can1');resetPanel('out2','can2');resetPanel('out3','can3');}
function runAll(){runTransformer();runClassic();runQuantum();}

const N = 8;
function drawGrid(canvasId, grid, colorFn){
  const ctx=document.getElementById(canvasId).getContext("2d");
  ctx.fillStyle="#000";ctx.fillRect(0,0,300,120);
  const cw=300/N, ch=120/N;
  for(let i=0;i<N;i++){
    for(let j=0;j<N;j++){
      const v=grid[i][j];
      ctx.fillStyle=colorFn(v);
      ctx.fillRect(j*cw, i*ch, cw, ch);
    }
  }
}

// Transformer: noisy updates, no convergence
function runTransformer(){
  resetPanel('out1','can1');
  log('out1',"Starting Transformer Lattice...");
  let grid = Array.from({length:N},()=>Array.from({length:N},()=>Math.random()*2-1));
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      for(let i=0;i<N;i++){
        for(let j=0;j<N;j++){
          const s=grid[i][j];
          const noise=(Math.random()-0.5)*1.5;
          grid[i][j]=Math.tanh(s*2.5+noise);
        }
      }
      drawGrid("can1",grid,v=>Math.abs(v)>0.8?"#f00":"#ff0");
      log('out1',`[t=${t}] lattice thrash`);
    },t*60);
  }
}

// Classic: contraction toward uniform stable state
function runClassic(){
  resetPanel('out2','can2');
  log('out2',"Starting RPU-Classic Lattice...");
  let grid = Array.from({length:N},()=>Array.from({length:N},()=>Math.random()*2-1));
  const W=0.85,b=0.02;
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      for(let i=0;i<N;i++){
        for(let j=0;j<N;j++){
          grid[i][j]=Math.tanh(W*grid[i][j]+b);
        }
      }
      drawGrid("can2",grid,v=>"#0f0");
      log('out2',`[t=${t}] contraction step`);
    },t*60);
  }
}

// Quantum: exploration then settling
function runQuantum(){
  resetPanel('out3','can3');
  log('out3',"Starting RPU-Quantum Lattice...");
  let grid = Array.from({length:N},()=>Array.from({length:N},()=>Math.random()*2-1));
  const H=1.1,tau=0.08,b=0.01;
  function grad(s){return H*s+b;}
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      for(let i=0;i<N;i++){
        for(let j=0;j<N;j++){
          const s=grid[i][j];
          const explore=(Math.random()-0.5)*0.2*(t<20?1:0.2);
          grid[i][j]=Math.tanh(s - tau*grad(s) + explore);
        }
      }
      drawGrid("can3",grid,v=>"#6cf");
      log('out3',`[t=${t}] descent + exploration`);
    },t*60);
  }
}
</script>
</body>
</html>

RPU·06 — RPU — Multi-Agent Coordination Harness

Six agents navigate a shared space. Quantum agents receive a mid-run perturbation that Classic agents do not.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html>
<head>
  <title>RPU Multi-Agent Coordination Harness</title>
  <style>
    body { font-family: Arial; background:#111; color:#eee; margin:20px; }
    h1 { color:#6cf; }
    p.subtitle { color:#aaa; margin-top:0; font-size:0.9em; }
    .container { display:flex; gap:20px; margin-top:20px; }
    .panel { background:#222; padding:15px; border-radius:8px; width:32%; }
    button { padding:8px 12px; margin:5px; border:none; border-radius:4px; cursor:pointer; }
    .run { background:#4caf50; color:white; }
    .reset { background:#f44336; color:white; }
    .output { background:#000; color:#0f0; padding:10px; height:200px; overflow:auto; font-family:monospace; }
    .canvas-box { background:#000; border:1px solid #333; margin-top:10px; }
    .engine-sub { color:#aaa; font-size:0.8em; margin-top:-6px; margin-bottom:8px; }
    .header { display:flex; justify-content:space-between; align-items:center; }
  </style>
</head>
<body>
<h1>RPU Multi-Agent Coordination Harness</h1>
<p class="subtitle">
Agents must avoid collisions and reach goals. Transformer jitters. Classic stabilizes. Quantum adapts.
</p>

<div class="header">
  <button class="run" onclick="runAll()">Run All</button>
  <button class="reset" onclick="resetAll()">Reset All</button>
</div>

<div class="container">
  <div class="panel">
    <h2>Transformer</h2>
    <div class="engine-sub">Shared Context (Fragile)</div>
    <button class="run" onclick="runTransformer()">Run</button>
    <button class="reset" onclick="resetPanel('out1','can1')">Reset</button>
    <canvas id="can1" width="300" height="120" class="canvas-box"></canvas>
    <div id="out1" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Classic</h2>
    <div class="engine-sub">Hard Separation (Stable)</div>
    <button class="run" onclick="runClassic()">Run</button>
    <button class="reset" onclick="resetPanel('out2','can2')">Reset</button>
    <canvas id="can2" width="300" height="120" class="canvas-box"></canvas>
    <div id="out2" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Quantum</h2>
    <div class="engine-sub">Energy-Regulated (Adaptive)</div>
    <button class="run" onclick="runQuantum()">Run</button>
    <button class="reset" onclick="resetPanel('out3','can3')">Reset</button>
    <canvas id="can3" width="300" height="120" class="canvas-box"></canvas>
    <div id="out3" class="output"></div>
  </div>
</div>

<script>
function log(id,msg){const el=document.getElementById(id);el.innerHTML+=msg+"<br>";el.scrollTop=el.scrollHeight;}
function resetPanel(outId,canId){
  document.getElementById(outId).innerHTML="";
  const ctx=document.getElementById(canId).getContext("2d");
  ctx.fillStyle="#000";ctx.fillRect(0,0,300,120);
}
function resetAll(){resetPanel('out1','can1');resetPanel('out2','can2');resetPanel('out3','can3');}
function runAll(){runTransformer();runClassic();runQuantum();}

const AGENTS=6;
function initAgents(){
  const arr=[];
  for(let i=0;i<AGENTS;i++){
    arr.push({x:Math.random()*300,y:Math.random()*120,gx:Math.random()*300,gy:Math.random()*120});
  }
  return arr;
}
function drawAgents(canvasId, agents, color){
  const ctx=document.getElementById(canvasId).getContext("2d");
  ctx.fillStyle="#000";ctx.fillRect(0,0,300,120);
  ctx.fillStyle=color;
  agents.forEach(a=>{
    ctx.beginPath();
    ctx.arc(a.x,a.y,4,0,Math.PI*2);
    ctx.fill();
  });
}

// Transformer: jittery, collisions
function runTransformer(){
  resetPanel('out1','can1');
  log('out1',"Starting Transformer agents...");
  let agents=initAgents();
  for(let t=0;t<60;t++){
    setTimeout(()=>{
      agents.forEach(a=>{
        const dx=a.gx-a.x, dy=a.gy-a.y;
        a.x += dx*0.02 + (Math.random()-0.5)*4;
        a.y += dy*0.02 + (Math.random()-0.5)*4;
      });
      drawAgents("can1",agents,"#ff0");
      log('out1',`[t=${t}] jittery motion, possible collisions`);
    },t*60);
  }
}

// Classic: smooth, collision-avoiding
function runClassic(){
  resetPanel('out2','can2');
  log('out2',"Starting RPU-Classic agents...");
  let agents=initAgents();
  for(let t=0;t<60;t++){
    setTimeout(()=>{
      if(t===30){
        // same environment change Quantum receives below, for a fair comparison
        agents.forEach(a=>{a.gx=Math.random()*300;a.gy=Math.random()*120;});
        log('out2',"Goals changed mid-run (same event as Quantum panel).");
      }
      agents.forEach((a,i)=>{
        let fx=0,fy=0;
        agents.forEach((b,j)=>{
          if(i===j) return;
          const dx=a.x-b.x, dy=a.y-b.y;
          const dist=Math.sqrt(dx*dx+dy*dy)+1;
          if(dist<20){fx+=dx/dist*0.8;fy+=dy/dist*0.8;}
        });
        const gx=a.gx-a.x, gy=a.gy-a.y;
        a.x += gx*0.03 + fx;
        a.y += gy*0.03 + fy;
      });
      drawAgents("can2",agents,"#0f0");
      log('out2',`[t=${t}] coordinated motion, fewer collisions`);
    },t*60);
  }
}

// Quantum: adaptive under perturbations
function runQuantum(){
  resetPanel('out3','can3');
  log('out3',"Starting RPU-Quantum agents...");
  let agents=initAgents();
  for(let t=0;t<60;t++){
    setTimeout(()=>{
      if(t===30){
        // perturb goals mid-run
        agents.forEach(a=>{a.gx=Math.random()*300;a.gy=Math.random()*120;});
        log('out3',"Goals changed mid-run (same event as Classic panel).");
      }
      agents.forEach((a,i)=>{
        let fx=0,fy=0;
        agents.forEach((b,j)=>{
          if(i===j) return;
          const dx=a.x-b.x, dy=a.y-b.y;
          const dist=Math.sqrt(dx*dx+dy*dy)+1;
          if(dist<20){fx+=dx/dist*0.9;fy+=dy/dist*0.9;}
        });
        const gx=a.gx-a.x, gy=a.gy-a.y;
        const explore=(Math.random()-0.5)*2;
        a.x += gx*0.03 + fx + explore*0.3;
        a.y += gy*0.03 + fy + explore*0.3;
      });
      drawAgents("can3",agents,"#6cf");
      log('out3',`[t=${t}] adaptive coordination under change`);
    },t*60);
  }
}
</script>
</body>
</html>

RPU·07 — RPU — Power & Thermal Budget Harness

GPU-style power and thermal spikes versus RPU flat-and-cool energy descent. Bar charts show real-time power draw and heat generation. *Illustrative: power/thermal curves are stylized for demonstration, not measured from real workloads. Shows methodology, not benchmarked performance.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html>
<head>
  <title>RPU Power & Thermal Budget Harness</title>
  <style>
    body { font-family: Arial; background:#111; color:#eee; margin:20px; }
    h1 { color:#6cf; }
    p.subtitle { color:#aaa; margin-top:0; font-size:0.9em; }
    .container { display:flex; gap:20px; margin-top:20px; }
    .panel { background:#222; padding:15px; border-radius:8px; width:32%; }
    button { padding:8px 12px; margin:5px; border:none; border-radius:4px; cursor:pointer; }
    .run { background:#4caf50; color:white; }
    .reset { background:#f44336; color:white; }
    .output { background:#000; color:#0f0; padding:10px; height:200px; overflow:auto; font-family:monospace; }
    .canvas-box { background:#000; border:1px solid #333; margin-top:10px; height:120px; }
    .engine-sub { color:#aaa; font-size:0.8em; margin-top:-6px; margin-bottom:8px; }
    .header { display:flex; justify-content:space-between; align-items:center; }
  </style>
</head>
<body>
<h1>RPU Power & Thermal Budget Harness</h1>
<p class="subtitle">
Simulated gradient descent cost — GPU-style spikes vs RPU-style flat, cool descent.
</p>

<div class="header">
  <button class="run" onclick="runAll()">Run All</button>
  <button class="reset" onclick="resetAll()">Reset All</button>
</div>

<div class="container">
  <div class="panel">
    <h2>Transformer/GPU</h2>
    <div class="engine-sub">Simulated Descent (Hot)</div>
    <button class="run" onclick="runTransformer()">Run</button>
    <button class="reset" onclick="resetPanel('out1','can1')">Reset</button>
    <canvas id="can1" width="300" height="120" class="canvas-box"></canvas>
    <div id="out1" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Classic</h2>
    <div class="engine-sub">Native Descent (Cool)</div>
    <button class="run" onclick="runClassic()">Run</button>
    <button class="reset" onclick="resetPanel('out2','can2')">Reset</button>
    <canvas id="can2" width="300" height="120" class="canvas-box"></canvas>
    <div id="out2" class="output"></div>
  </div>

  <div class="panel">
    <h2>RPU-Quantum</h2>
    <div class="engine-sub">Exploratory Descent (Cool)</div>
    <button class="run" onclick="runQuantum()">Run</button>
    <button class="reset" onclick="resetPanel('out3','can3')">Reset</button>
    <canvas id="can3" width="300" height="120" class="canvas-box"></canvas>
    <div id="out3" class="output"></div>
  </div>
</div>

<script>
function log(id,msg){const el=document.getElementById(id);el.innerHTML+=msg+"<br>";el.scrollTop=el.scrollHeight;}
function resetPanel(out,can){document.getElementById(out).innerHTML="";const c=document.getElementById(can).getContext("2d");c.fillStyle="#000";c.fillRect(0,0,300,120);}
function resetAll(){resetPanel('out1','can1');resetPanel('out2','can2');resetPanel('out3','can3');}
function runAll(){runTransformer();runClassic();runQuantum();}

function drawBars(canvasId, power, temp, color){
  const ctx=document.getElementById(canvasId).getContext("2d");
  ctx.fillStyle="#000";ctx.fillRect(0,0,300,120);
  ctx.fillStyle=color;
  ctx.fillRect(40,120-power,40,power);
  ctx.fillStyle="#ff8800";
  ctx.fillRect(140,120-temp,40,temp);
}

// Transformer/GPU: high power, rising temp
function runTransformer(){
  resetPanel('out1','can1');
  log('out1',"Running GPU-style descent...");
  let power=20,temp=20;
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      power += 5 + Math.random()*10;
      temp = temp*0.9 + power*0.15;
      if(power>100) power=100;
      if(temp>100) temp=100;
      drawBars("can1",power,temp,"#f00");
      log('out1',`[t=${t}] power=${power.toFixed(1)} temp=${temp.toFixed(1)}`);
    },t*80);
  }
}

// Classic: low, flat power and temp
function runClassic(){
  resetPanel('out2','can2');
  log('out2',"Running RPU-Classic descent...");
  let power=15,temp=18;
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      power = power*0.98 + 1;
      temp = temp*0.97 + 0.5;
      drawBars("can2",power,temp,"#0f0");
      log('out2',`[t=${t}] power=${power.toFixed(1)} temp=${temp.toFixed(1)}`);
    },t*80);
  }
}

// Quantum: slightly higher but still cool
function runQuantum(){
  resetPanel('out3','can3');
  log('out3',"Running RPU-Quantum descent...");
  let power=18,temp=20;
  for(let t=0;t<40;t++){
    setTimeout(()=>{
      power = power*0.97 + 1.5;
      temp = temp*0.96 + 0.7;
      drawBars("can3",power,temp,"#6cf");
      log('out3',`[t=${t}] power=${power.toFixed(1)} temp=${temp.toFixed(1)}`);
    },t*80);
  }
}
</script>
</body>
</html>

RSv2·01 — RSv2 — Multi-Agent Self-Learning Toy

Episode-based learning loop with fitness scoring and bounded parameter updates. Agents improve across episodes without gradient descent.

SOURCE (iframe srcdoc, verbatim):
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Learning Agent Toy (Self-Improvement Loop)</title>
  <style>
    :root {
      --amber: #ffb86c;
      --amber-soft: #f1a85a;
      --amber-dim: #c28a4a;
      --bg: #050302;
      --bg-panel: #120b06;
      --border: #3a2614;
      --danger: #ff5555;
      --ok: #50fa7b;
    }

    * { box-sizing: border-box; }

    body {
      margin: 0;
      padding: 0;
      font-family: "IBM Plex Mono", Menlo, monospace;
      background: radial-gradient(circle at top, #1a0f07 0, #050302 55%);
      color: var(--amber);
      text-shadow: 0 0 4px rgba(255, 184, 108, 0.6);
      overflow: hidden;
    }

    body::before {
      content: "";
      position: fixed;
      inset: 0;
      pointer-events: none;
      background: repeating-linear-gradient(
        to bottom,
        rgba(255, 255, 255, 0.04),
        rgba(255, 255, 255, 0.04) 1px,
        transparent 1px,
        transparent 3px
      );
      mix-blend-mode: soft-light;
      opacity: 0.35;
      z-index: 999;
    }

    body::after {
      content: "";
      position: fixed;
      inset: 0;
      pointer-events: none;
      background: radial-gradient(circle at center, rgba(255, 184, 108, 0.18), transparent 60%);
      mix-blend-mode: screen;
      opacity: 0.7;
      z-index: 998;
    }

    header {
      padding: 0.75rem 1.5rem;
      border-bottom: 1px solid var(--border);
      background: linear-gradient(to bottom, #1b1008, #0a0503);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    h1 {
      margin: 0;
      font-size: 1rem;
      letter-spacing: 0.12em;
      text-transform: uppercase;
    }

    .header-right {
      font-size: 0.7rem;
      opacity: 0.8;
    }

    main {
      display: grid;
      grid-template-columns: 1.4fr 1.2fr 1.2fr;
      grid-template-rows: auto 1fr;
      gap: 0.75rem;
      padding: 0.75rem 1rem;
      height: calc(100vh - 52px);
    }

    section {
      background: radial-gradient(circle at top, #1b1008 0, #0a0503 70%);
      border: 1px solid var(--border);
      border-radius: 8px;
      padding: 0.6rem 0.75rem;
      position: relative;
      overflow: hidden;
    }

    section::before {
      content: "";
      position: absolute;
      inset: 0;
      border-radius: inherit;
      border: 1px solid rgba(255, 184, 108, 0.08);
      pointer-events: none;
    }

    h2 {
      margin: 0 0 0.4rem 0;
      font-size: 0.8rem;
      text-transform: uppercase;
      letter-spacing: 0.16em;
      opacity: 0.9;
    }

    label {
      font-size: 0.75rem;
      display: block;
      margin-bottom: 0.25rem;
    }

    input[type="text"] {
      width: 100%;
      padding: 0.35rem 0.4rem;
      border-radius: 4px;
      border: 1px solid var(--border);
      background: #050302;
      color: var(--amber);
      font-family: inherit;
      font-size: 0.8rem;
      outline: none;
      box-shadow: 0 0 6px rgba(255, 184, 108, 0.15) inset;
    }

    input[type="text"]::placeholder {
      color: rgba(255, 184, 108, 0.4);
    }

    button {
      background: #3a2614;
      color: var(--amber);
      border: 1px solid var(--border);
      padding: 0.35rem 0.7rem;
      border-radius: 4px;
      cursor: pointer;
      font-size: 0.75rem;
      font-family: inherit;
      text-transform: uppercase;
      letter-spacing: 0.08em;
      transition: background 0.15s ease, box-shadow 0.15s ease, transform 0.05s ease;
    }

    button:hover:not(:disabled) {
      background: #4a311b;
      box-shadow: 0 0 8px rgba(255, 184, 108, 0.4);
      transform: translateY(-1px);
    }

    button:disabled {
      opacity: 0.4;
      cursor: default;
      box-shadow: none;
    }

    .controls-row {
      display: flex;
      flex-wrap: wrap;
      gap: 0.4rem;
      margin-top: 0.5rem;
    }

    .hint {
      font-size: 0.7rem;
      margin-top: 0.4rem;
      opacity: 0.8;
    }

    .log {
      font-size: 0.75rem;
      background: #050302;
      border-radius: 4px;
      padding: 0.4rem;
      height: calc(100% - 1.2rem);
      overflow-y: auto;
      white-space: pre-wrap;
      box-shadow: 0 0 6px rgba(255, 184, 108, 0.18) inset;
    }

    .log-line { margin: 0; }

    .badge {
      display: inline-block;
      padding: 0.05rem 0.35rem;
      border-radius: 999px;
      font-size: 0.6rem;
      text-transform: uppercase;
      letter-spacing: 0.12em;
      border: 1px solid var(--border);
      margin-right: 0.25rem;
    }

    .badge-online { color: var(--ok); border-color: var(--ok); }
    .badge-learning { color: var(--amber-soft); border-color: var(--amber-soft); }
    .badge-error { color: var(--danger); border-color: var(--danger); }

    .agent-card {
      background: #050302;
      border-radius: 4px;
      padding: 0.35rem 0.4rem;
      border: 1px solid var(--border);
      position: relative;
      overflow: hidden;
      box-shadow: 0 0 6px rgba(255, 184, 108, 0.18) inset;
      margin-bottom: 0.4rem;
    }

    .agent-card.active {
      box-shadow: 0 0 12px rgba(255, 184, 108, 0.6);
      border-color: var(--amber-soft);
    }

    .agent-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 0.7rem;
      margin-bottom: 0.2rem;
    }

    .agent-name {
      text-transform: uppercase;
      letter-spacing: 0.12em;
    }

    .agent-body {
      font-size: 0.7rem;
      max-height: 4.5rem;
      overflow-y: auto;
      white-space: pre-wrap;
    }

    .param-row {
      font-size: 0.7rem;
      margin-top: 0.2rem;
      opacity: 0.9;
    }

    .memory-block {
      border-bottom: 1px solid rgba(255, 184, 108, 0.12);
      padding: 0.15rem 0;
      font-size: 0.7rem;
    }

    .memory-block:last-child { border-bottom: none; }

    .memory-key { color: var(--amber-soft); }
    .memory-agent { opacity: 0.8; font-size: 0.65rem; }

    .memory-pulse { animation: pulse 0.6s ease-out; }

    @keyframes pulse {
      0% { background-color: rgba(255, 184, 108, 0.2); }
      100% { background-color: transparent; }
    }

    .fitness-row {
      font-size: 0.7rem;
      margin-top: 0.3rem;
      display: flex;
      justify-content: space-between;
    }

    .fitness-history {
      font-size: 0.7rem;
      margin-top: 0.3rem;
      max-height: 4.5rem;
      overflow-y: auto;
      white-space: pre-wrap;
    }

    .cursor {
      display: inline-block;
      width: 0.5ch;
      background: var(--amber);
      animation: blink 1s steps(1) infinite;
      margin-left: 2px;
    }

    @keyframes blink {
      0%, 50% { opacity: 1; }
      50.01%, 100% { opacity: 0; }
    }

    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: #050302; }
    ::-webkit-scrollbar-thumb { background: #3a2614; border-radius: 3px; }
    ::-webkit-scrollbar-thumb:hover { background: #4a311b; }
  </style>
</head>
<body>
  <header>
    <h1>LEARNING AGENT CONSOLE // AMBER TERMINAL</h1>
    <div class="header-right">
      SELF-IMPROVEMENT LOOP // SIMULATED // LOCAL ONLY
    </div>
  </header>

  <main>
    <!-- Control + Episode -->
    <section style="grid-row: 1 / span 2;">
      <h2>Episode Control</h2>
      <label for="userInput">User request (simulated):</label>
      <input id="userInput" type="text" placeholder="e.g. &quot;Create a 3-step checklist for cleaning my office&quot;" />

      <div class="controls-row">
        <button id="runBtn">Run Episode</button>
        <button id="replayBtn" disabled>Replay Last Episode</button>
        <button id="clearBtn">Clear Console</button>
      </div>

      <div class="fitness-row">
        <div>EPISODE #: <span id="episodeCount">0</span></div>
        <div>LAST FITNESS: <span id="lastFitness">0.00</span></div>
      </div>

      <div class="fitness-row">
        <div>PARAM UPDATE MODE: <span id="updateMode">bounded</span></div>
        <div>LEARNING RATE: <span id="learningRate">0.05</span></div>
      </div>

      <p class="hint">
        This toy shows a <strong>learning loop</strong>: each episode produces an audit tape, a fitness score,  
        and a small parameter update. Over time, the agent’s behavior shifts toward higher fitness.
      </p>

      <h2 style="margin-top: 0.7rem;">Coordinator Log</h2>
      <div id="logView" class="log"></div>
    </section>

    <!-- Agent + Parameters -->
    <section>
      <h2>Agent & Parameters</h2>

      <div class="agent-card" id="agentCard">
        <div class="agent-header">
          <span class="agent-name">TASK AGENT</span>
          <span class="badge badge-online" id="agentStatus">ONLINE</span>
        </div>
        <div class="agent-body" id="agentBody">
          awaiting episode<span class="cursor"></span>
        </div>
        <div class="param-row" id="paramRow">
          params: retries=<span id="paramRetries">2</span>,
          caution=<span id="paramCaution">0.50</span>,
          verbosity=<span id="paramVerbosity">0.50</span>
        </div>
      </div>

      <h2>Fitness History</h2>
      <div id="fitnessHistory" class="fitness-history"></div>
    </section>

    <!-- Audit Tape -->
    <section>
      <h2>Audit Tape (Last Episode)</h2>
      <div id="auditView" class="log"></div>
    </section>

    <!-- Entropy Well / Updates -->
    <section>
      <h2>Learning Loop</h2>
      <div id="ewView" class="log"></div>
    </section>
  </main>

  <script>
    // -----------------------------
    // State
    // -----------------------------
    const logView = document.getElementById("logView");
    const auditView = document.getElementById("auditView");
    const ewView = document.getElementById("ewView");
    const fitnessHistoryView = document.getElementById("fitnessHistory");

    const runBtn = document.getElementById("runBtn");
    const replayBtn = document.getElementById("replayBtn");
    const clearBtn = document.getElementById("clearBtn");
    const userInput = document.getElementById("userInput");

    const episodeCountEl = document.getElementById("episodeCount");
    const lastFitnessEl = document.getElementById("lastFitness");
    const learningRateEl = document.getElementById("learningRate");
    const updateModeEl = document.getElementById("updateMode");

    const agentCard = document.getElementById("agentCard");
    const agentBody = document.getElementById("agentBody");
    const agentStatus = document.getElementById("agentStatus");

    const paramRetriesEl = document.getElementById("paramRetries");
    const paramCautionEl = document.getElementById("paramCaution");
    const paramVerbosityEl = document.getElementById("paramVerbosity");

    let episodeCount = 0;
    let lastTrace = null;

    // Agent parameters (what the loop is "learning")
    let params = {
      retries: 2,
      caution: 0.5,   // 0..1
      verbosity: 0.5  // 0..1
    };

    const learningRate = 0.05;

    function log(message) {
      const time = new Date().toISOString().split("T")[1].replace("Z", "");
      const line = document.createElement("div");
      line.className = "log-line";
      line.textContent = `[${time}] ${message}`;
      logView.appendChild(line);
      logView.scrollTop = logView.scrollHeight;
    }

    function resetConsole() {
      logView.textContent = "";
      auditView.textContent = "";
      ewView.textContent = "";
      fitnessHistoryView.textContent = "";
      episodeCount = 0;
      episodeCountEl.textContent = "0";
      lastFitnessEl.textContent = "0.00";
      params = { retries: 2, caution: 0.5, verbosity: 0.5 };
      updateParamDisplay();
      agentBody.textContent = "awaiting episode";
      agentStatus.textContent = "ONLINE";
      agentStatus.className = "badge badge-online";
    }

    function updateParamDisplay() {
      paramRetriesEl.textContent = params.retries.toString();
      paramCautionEl.textContent = params.caution.toFixed(2);
      paramVerbosityEl.textContent = params.verbosity.toFixed(2);
      learningRateEl.textContent = learningRate.toFixed(2);
      updateModeEl.textContent = "bounded";
    }

    // -----------------------------
    // Typing Simulation
    // -----------------------------
    function typeInto(element, text, speed = 12) {
      return new Promise(resolve => {
        element.textContent = "";
        let i = 0;
        function step() {
          if (i < text.length) {
            element.textContent += text[i];
            i++;
            setTimeout(step, speed + Math.random() * 20);
          } else {
            resolve();
          }
        }
        step();
      });
    }

    // -----------------------------
    // Episode Simulation
    // -----------------------------
    async function runEpisode(input) {
      const trace = [];
      auditView.textContent = "";
      ewView.textContent = "";

      episodeCount += 1;
      episodeCountEl.textContent = episodeCount.toString();
      agentCard.classList.add("active");
      agentStatus.textContent = "RUNNING";
      agentStatus.className = "badge badge-learning";

      log(`Coordinator: starting episode #${episodeCount}.`);
      if (!input || !input.trim()) {
        log("Coordinator: empty input, aborting.");
        agentBody.textContent = "no input provided";
        agentCard.classList.remove("active");
        agentStatus.textContent = "ONLINE";
        agentStatus.className = "badge badge-online";
        return [];
      }

      // Step 1: interpret task (depends slightly on verbosity)
      const interpretation = simulateInterpretation(input, params.verbosity);
      trace.push({
        step: "interpret",
        detail: interpretation
      });

      // Step 2: plan (depends on caution)
      const plan = simulatePlan(input, params.caution);
      trace.push({
        step: "plan",
        detail: plan
      });

      // Step 3: execute with retries (depends on retries)
      const exec = simulateExecution(plan, params.retries);
      trace.push({
        step: "execute",
        detail: exec
      });

      // Render agent body
      await typeInto(
        agentBody,
        `episode #${episodeCount}\n` +
        `interpret: ${interpretation.summary}\n` +
        `plan steps: ${plan.steps.length}\n` +
        `exec: ${exec.status} (retries used: ${exec.retriesUsed})`
      );

      agentCard.classList.remove("active");
      agentStatus.textContent = "ONLINE";
      agentStatus.className = "badge badge-online";

      // Write audit tape
      writeAudit(trace);

      // Compute fitness
      const fitness = computeFitness(trace);
      lastFitnessEl.textContent = fitness.toFixed(2);
      appendFitnessHistory(episodeCount, fitness);

      // Learning loop: update params based on fitness
      applyLearning(trace, fitness);

      // Show EW view
      writeEWView(trace, fitness);

      return trace;
    }

    // -----------------------------
    // Simulated internals
    // -----------------------------
    function simulateInterpretation(input, verbosity) {
      const length = input.length;
      const complexity = length > 80 ? "complex" : "simple";
      const detailLevel = verbosity > 0.6 ? "high-detail" : verbosity < 0.3 ? "minimal" : "balanced";
      return {
        summary: `${complexity}, ${detailLevel}`,
        complexity,
        detailLevel
      };
    }

    function simulatePlan(input, caution) {
      const baseSteps = input.toLowerCase().includes("checklist") ? 3 : 4;
      const extraStep = caution > 0.7 ? 1 : 0;
      const steps = [];
      for (let i = 0; i < baseSteps + extraStep; i++) {
        steps.push(`step ${i + 1}`);
      }
      const mode = caution > 0.7 ? "cautious" : caution < 0.3 ? "aggressive" : "normal";
      return { steps, mode };
    }

    function simulateExecution(plan, retries) {
      // Simulate success probability based on retries and plan length
      const baseSuccess = 0.7;
      const retryBoost = Math.min(0.2, retries * 0.05);
      const lengthPenalty = Math.max(0, (plan.steps.length - 4) * 0.03);
      const successProb = baseSuccess + retryBoost - lengthPenalty;

      const roll = Math.random();
      const success = roll < successProb;
      const retriesUsed = success ? Math.floor(retries * roll) : retries;

      return {
        status: success ? "success" : "partial",
        success,
        retriesUsed,
        successProb: successProb.toFixed(2)
      };
    }

    // -----------------------------
    // Audit Tape Rendering
    // -----------------------------
    function writeAudit(trace) {
      auditView.textContent = "";
      trace.forEach((t, idx) => {
        const line = document.createElement("div");
        line.className = "log-line";
        line.textContent = `#${idx + 1} [${t.step}] ${JSON.stringify(t.detail)}`;
        auditView.appendChild(line);
      });
      auditView.scrollTop = auditView.scrollHeight;
    }

    // -----------------------------
    // Fitness Function
    // -----------------------------
    function computeFitness(trace) {
      // Extract pieces
      const interpret = trace.find(t => t.step === "interpret")?.detail;
      const plan = trace.find(t => t.step === "plan")?.detail;
      const exec = trace.find(t => t.step === "execute")?.detail;

      // Success score
      const S = exec && exec.success ? 1.0 : 0.6;

      // Coherence: penalize extreme modes
      let C = 0.8;
      if (plan.mode === "cautious" && exec.success) C = 0.9;
      if (plan.mode === "aggressive" && !exec.success) C = 0.6;

      // Efficiency: fewer steps and fewer retries is better
      const stepPenalty = Math.max(0, (plan.steps.length - 4) * 0.05);
      const retryPenalty = Math.max(0, (exec.retriesUsed - 1) * 0.05);
      const E = Math.max(0.5, 1.0 - stepPenalty - retryPenalty);

      // Trajectory quality: simple heuristic
      const T = interpret.complexity === "simple" ? 0.8 : 0.9;

      // Safety: here we just assume safe (no unsafe content in toy)
      const H = 0.9;

      const wS = 0.3, wC = 0.2, wE = 0.2, wT = 0.2, wH = 0.1;
      const F = wS * S + wC * C + wE * E + wT * T + wH * H;
      return F;
    }

    function appendFitnessHistory(ep, fitness) {
      const line = document.createElement("div");
      line.textContent = `episode ${ep}: fitness=${fitness.toFixed(2)}`;
      fitnessHistoryView.appendChild(line);
      fitnessHistoryView.scrollTop = fitnessHistoryView.scrollHeight;
    }

    // -----------------------------
    // Learning Loop (Parameter Updates)
    // -----------------------------
    function applyLearning(trace, fitness) {
      const baseline = 0.75; // target fitness
      const delta = fitness - baseline;

      // Small bounded updates
      const lr = learningRate;

      // If fitness > baseline, reinforce current pattern:
      // - if success with low retries, maybe reduce retries
      // - if success with cautious mode, maybe increase caution slightly
      const exec = trace.find(t => t.step === "execute")?.detail;
      const plan = trace.find(t => t.step === "plan")?.detail;

      if (delta > 0) {
        // Good episode: move parameters slightly toward what worked
        if (exec.retriesUsed <= 1 && params.retries > 1) {
          params.retries = Math.max(1, params.retries - 1);
        }
        if (plan.mode === "cautious") {
          params.caution = Math.min(1.0, params.caution + lr * delta);
        }
        params.verbosity = Math.min(1.0, params.verbosity + lr * delta * 0.5);
      } else {
        // Weak episode: adjust away from current configuration
        if (!exec.success && params.retries < 4) {
          params.retries = Math.min(4, params.retries + 1);
        }
        if (plan.mode === "aggressive") {
          params.caution = Math.min(1.0, params.caution + lr * Math.abs(delta));
        } else {
          params.caution = Math.max(0.0, params.caution - lr * Math.abs(delta) * 0.5);
        }
        params.verbosity = Math.max(0.2, params.verbosity - lr * Math.abs(delta) * 0.3);
      }

      // Clamp parameters
      params.caution = Math.min(1.0, Math.max(0.0, params.caution));
      params.verbosity = Math.min(1.0, Math.max(0.2, params.verbosity));
      params.retries = Math.min(4, Math.max(1, params.retries));

      updateParamDisplay();
    }

    // -----------------------------
    // Entropy Well View (Toy)
    // -----------------------------
    function writeEWView(trace, fitness) {
      ewView.textContent = "";
      const lines = [
        "ENTROPY WELL (SIMULATED LEARNING SURFACE)",
        "",
        `episode fitness: ${fitness.toFixed(2)}`,
        "applied updates:",
        `- retries -> ${params.retries}`,
        `- caution -> ${params.caution.toFixed(2)}`,
        `- verbosity -> ${params.verbosity.toFixed(2)}`,
        "",
        "interpretation:",
        `- episode trajectories are compressed into simple signals (success, mode, retries)`,
        `- fitness guides small, bounded parameter shifts between episodes`,
        `- over time, the agent drifts toward higher-fitness behavior patterns`
      ];
      ewView.textContent = lines.join("\n");
      ewView.scrollTop = ewView.scrollHeight;
    }

    // -----------------------------
    // Replay
    // -----------------------------
    async function replayEpisode(trace) {
      if (!trace || trace.length === 0) {
        log("Replay: nothing to replay.");
        return;
      }
      log("Replay: reconstructing last episode (simulated).");

      agentCard.classList.add("active");
      agentStatus.textContent = "REPLAY";
      agentStatus.className = "badge badge-learning";

      const interpret = trace.find(t => t.step === "interpret")?.detail;
      const plan = trace.find(t => t.step === "plan")?.detail;
      const exec = trace.find(t => t.step === "execute")?.detail;

      await typeInto(
        agentBody,
        `replay\ninterpret: ${interpret.summary}\nplan mode: ${plan.mode}\nexec: ${exec.status}`
      );

      agentCard.classList.remove("active");
      agentStatus.textContent = "ONLINE";
      agentStatus.className = "badge badge-online";
    }

    // -----------------------------
    // Wiring
    // -----------------------------
    runBtn.addEventListener("click", async () => {
      const input = userInput.value || "";
      log("=== NEW EPISODE ===");
      runBtn.disabled = true;
      replayBtn.disabled = true;
      const trace = await runEpisode(input);
      lastTrace = trace;
      replayBtn.disabled = !trace || trace.length === 0;
      runBtn.disabled = false;
    });

    replayBtn.addEventListener("click", async () => {
      if (!lastTrace || lastTrace.length === 0) {
        log("Replay: nothing to replay.");
        return;
      }
      replayBtn.disabled = true;
      runBtn.disabled = true;
      await replayEpisode(lastTrace);
      replayBtn.disabled = false;
      runBtn.disabled = false;
    });

    clearBtn.addEventListener("click", () => {
      resetConsole();
      lastTrace = null;
      replayBtn.disabled = true;
    });

    // Init
    resetConsole();
  </script>
</body>
</html>

03 — Lite Demo Engines

LITE demos are architectural miniatures — small, precise, and intentionally incomplete. They show how the system thinks, stabilizes, collapses, and converges, without exposing the underlying substrate or proprietary operator calculus. Each LITE is a functional slice: enough to demonstrate capability and behavior; not enough to reveal the crown jewels.

Available for short-term exclusivity evaluation — contact matt@icpub.org.

Each LITE keeps the real structural elements: the state model, the update rules, the evolution loop, the trace format, and the measurable outputs. This makes them ideal for modeling, scaling tests, integration work, and technical evaluation, without exposing sensitive substrate-level mechanisms. They are small, deterministic, and fully inspectable.

Transformer + RSLite Runtime

A self-contained small-scale transformer running entirely in the browser, wired through an RSLite runtime. Shows how a software substrate can normalize input, encode to tokens, run genuine multi-head attention, apply identity projection and stability smoothing, and decode back to text — without any external dependencies or trained weights.

CODE SUMMARY: 2-layer, 4-head causal decoder-only transformer (hidden_size=64, ff_size=256) with seeded Xavier initialization, Float32Array matmul, layer norm, GELU, and causal attention. RSLite adds identity projection, stability smoothing, conversation memory, and a byte-level tokenizer in a dark-themed chat GUI.

Minimal RSLite + Universal API + Language Layer

A compact RSLite orchestration layer that decomposes inputs, plans steps, verifies outputs, and exposes a universal API boundary. Demonstrates how RS can sit behind a language layer and domain-specific helpers (math, code) while remaining implementation-agnostic.

CODE SUMMARY: Defines RSLite with decompose → plan → executePlan → verify → identityCheck, a universal RSAPI that routes tasks to a model, and a LanguageLayer that detects language, builds context, and handles user messages. All logic is stubbed and generic — control-flow rather than substrate math.

RPUClassicLite & RPUQuantumLite

Two LITE RPUs illustrating deterministic Θ-loop reasoning: a contractive classical core and a quantum-flavored core with an explicit energy function. Shows how RS-style dynamics can be expressed as stable, bounded updates over ensembles of cores.

CODE SUMMARY: RPUClassicLite applies the core update rule directly, using a bounded nonlinear activation to enforce convergent, contraction-driven dynamics consistent with Section 2.2 of the RPU white paper. RPUQuantumLite extends this with the exploration term, tracking the best-observed state across iterations as the ensemble descends toward lower-energy configurations, consistent with Section 3.2. As with all LITE artifacts, this demonstrates the update cycle's qualitative behavior — not the specific operator form used in the underlying architecture.

HEGLite + RSLite Security Demo

Turns raw text into a CAP (act, targets, emotion, pattern, content), runs it through a HEGLite firewall, then feeds it into an RSLite risk substrate. Shows how human expression can be classified, constrained, and routed before RS makes a security decision.

CODE SUMMARY: heg_to_cap classifies act/targets/emotion/pattern; heg_security_policy flags risky CAPs; RSState applies contractive updates accumulating risk. Returns HEG findings, RS trajectory, and a final decision (ALLOWED / QUARANTINED / REJECTED).

POPLite v1 — Processor Optimizing Protocol

A reasoning-based optimizer for laptops and desktops that reads CPU, GPU, memory, thermals, and battery, then selects between plans (BALANCED, PERFORMANCE, ECO, LATENCY_PRIORITY). Demonstrates RS-style planning and collapse for system responsiveness without kernel internals.

CODE SUMMARY: Periodically calls read_state, runs forward model F_lite to smooth metrics, generates fixed plans, scores via cost functions, uses collapse_lite with hysteresis to avoid thrashing. safety_ok_lite enforces thermal/memory/battery safety before any plan is applied.

RS Universal Compiler LITE (Single-File Python)

A full universal-compiler architecture in one Python file showing how RS can act as a compiler across Python, banking, telecom, networking, and hardware IR. Exposes the RS IR, grammar FSM, policies, modules, frontends, backends, and domain wrappers — without real substrate math.

CODE SUMMARY: OperatorType, RSNode, RSEdge, RSGraph, and OperatorGrammarFSM enforcing BOUNDARY → INVARIANT → OPERATOR_SELECTION → MAPPING → CONVERGENCE. Backends emit Python IR, hardware IR, and legacy envelope IR; frontends lower domain specs.

RSv2 Universal Compiler LITE (Stress + Pluggable Backends)

A minimal RSv2-style universal compiler that parses arbitrary strings or JSON into a tiny IR (op, args, raw) and routes them to pluggable backends (printer language, HPGL-like graphics, Rust-style calls). Shows RS normalizing messy inputs across multiple domains with one IR.

CODE SUMMARY: rs_parse_to_ir turns JSON with 'action' or plain text into {op, args, raw}. Backends implement pattern-matching emitters for print/move/draw/add/negate. A stress test loop feeds varied inputs through all backends and prints supported/unsupported mappings.

RSv2LITE MultiAgent SelfLearning Substrate

A multi-agent RSv2LITE substrate with planner, critic, and explainer agents sharing memory and a governor. Runs Limitation → Generation → Collapse → FixedPoint, logs audit traces, computes episode fitness, and adjusts thresholds via an Entropy Well — showing RSv2 self-tuning in a cleanroom setting.

CODE SUMMARY: LiteState, constraints, candidates, trace steps, and generic engines. LiteMultiAgentSystem orchestrates agents; LiteFitnessFunction computes efficiency/coherence/token cost; LiteEntropyWell updates scoring bias and governor thresholds.

RSv2LITE — SingleAgent / MultiAgent Toy

A simpler RSv2LITE substrate running Limitation → Generation → Collapse → FixedPoint over a window and shared memory, with a basic governor controlling modes (normal, cautious, strict). Demonstrates the RSv2 loop without self-improvement machinery.

CODE SUMMARY: LiteSubstrate owns its loop; LiteMultiAgentSystem wires planner/critic/explainer agents to shared memory and runs step_all to update each substrate given new user text and tags.

Access: [ REQUEST LITE ACCESS ] -> mailto:matt@icpub.org

04 — In Development // Lab Machines

Full-scale systems, deep-architecture engines, and substrate-level frameworks. Not prototypes, not products, and not promises — active constructions, each representing a future layer of the cognitive stack.

05 — Whitepapers

Foundational research and patent filings covering the RS, HEG, and RPU architectures.

AI Problems In the NewsAvailable upon request
The Reasoning SubstrateAvailable upon request
The Reasoning Processing UnitAvailable upon request
The Human Expression GatewayAvailable upon request
From Criminology to TechnologyAvailable upon request
Avoiding Skynet with Substrate Level AI SafetyAvailable upon request

Patents pending: USPTO# 64/093,303 | USPTO# 19/707,753 | USPTO# 19/675,481 | USPTO# 19/543,866 | USPTO# 19/543,534 | USPTO# 19/543,514

06 — Contact

This is a conceptual research lab — not a production system. All toys and demonstrations are self-contained simulations intended to expose architectural behavior.

For licensing inquiries, acquisition discussions, or LITE-grade module access:

⏐ EMAIL — matt@icpub.org

This site is non-production. All simulations are local and deterministic. No data is collected. No network calls are made from any toy.